题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
为什么要用next指针?
curr.next指向前一个元素后,我们想向后移动curr,如果没有next指针,我们无法再靠curr.next找到后一个元素(因为已经指向了前一个元素),所以需要next指针先占住curr的后一个元素。
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function ReverseList(pHead)
{
// write code here
let prev = null;
let current = pHead;
let next = pHead;
while(current){
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
module.exports = {
ReverseList : ReverseList
};