题目

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

思路

至少需要三个指针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;
}