剑指offer(15)反转链表

题目描述:

输入一个链表,反转链表后,输出新链表的表头。

解题代码:

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function ReverseList(pHead)
{
    // write code here
    if(pHead == null || pHead.next == null){
        return pHead;
    }
    //三个指针,pre指向前一个指针,pHead为当前指针,next为下一个指针
    var pre = null;
    var next = null;
    //当前指针不为空时,一直用next指向其下一个结点,再将当前指针的next指向前一个指针完成链表的反转
    //操作完成后,用pre指向当前节点,pHead指向next指向的下一个结点。当前结点为空时,pre指向的即为反转后的链表的表头
    while(pHead != null){
        next = pHead.next;
        pHead.next = pre;
        pre = pHead;
        pHead = next;
    }
    return pre;
}
原文地址:https://www.cnblogs.com/3yleaves/p/9594581.html