题目描述:
输入一个链表,反转链表后,输出新链表的表头。
题目分析:
1->2->3->4->5,遍历链表,把1的next置为null,2的next置为1,以此类推,5的next置为4。得到反转链表。需要考虑链表只有1个元素的情况。图中有具体的每步迭代的思路,最后输出pre而不是pHead是因为最后一次迭代后pHead已经指向null了,而pre是完整的反向链表。
代码:
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function ReverseList(pHead)
{
// write code here
if(pHead == null){
return null;
}
let pre = null,next = null;
while(pHead !== null){
next = pHead.next;
pHead.next = pre;
pre = pHead;
pHead = next;
}
return pre;
}