反转链表

剑指offer-牛客网

Posted by Y. on November 5, 2018

反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

时间限制:1秒 空间限制:32768K

代码

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function ReverseList(pHead)
{
    // write code here
    var pre = null, nextNode = null;
    if(pHead == null) return pHead;
    while(pHead != null) {
        nextNode = pHead.next;
        pHead.next = pre;
        pre = pHead;
        pHead = nextNode;
    }
    return pre;
}