题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
function ListNode(x){
this.val = x;
this.next = null;
}
//递归
/*
function ReverseList(pHead)
{
//空链表 或者只有一个节点的情况 终止条件就是链表为空,或者是链表没有尾结点的时候,直接返回
if(!pHead || !pHead.next) return pHead;
let newhead = ReverseList(pHead.next);
pHead.next.next = pHead; //曾经为头部的phead的下一个节点的next 变为phead
pHead.next = null;//曾经为头部的phead 变为尾
return newhead;
}
*/
function ReverseList(pHead)
{
if(!pHead || !pHead.next ) return pHead;
let previous = new ListNode(pHead.val);//newTail;
let node = pHead.next;
let temp;
while(node!==null){
temp = new ListNode(node.val);
temp.next = previous;
previous = temp;
node = node.next
}
return temp
}
module.exports = {
ReverseList : ReverseList
};