剑指offer(15)反转链表

题目描述

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

题目分析

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

代码

/* 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;
}

 

posted @ 2018-03-01 02:42  汕大小吴  阅读(1232)  评论(1编辑  收藏  举报