剑指offer(15)反转链表

时间:2023-03-09 16:31:06
剑指offer(15)反转链表

题目描述

输入一个链表,反转链表后,输出链表的所有元素。

题目分析

至少需要三个指针pPre(指向前一个结点)、pCurrent(指向当前的结点,在代码中就是pHead)、pPnext(指向后一个结点)。

代码

/* function ListNode(x){
this.val = x;
this.next = null;
}*/
function ReverseList(pHead) {
// write code here
let pPre = null,
pNext = null;
while (pHead !== null) {
pNext = pHead.next;
pHead.next = pPre;
pPre = pHead;
pHead = pNext;
}
return pPre;
}