算法刷题-反转链表

反转链表

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function ReverseList(pHead)
{	//双指针
    // write code here
    
    //pre current next 
    let pre = null
    let  next = null
    let current = pHead
    while(current){
           
           next = current.next //由于断开节点后就无法访问到后面的节点 ,断开之前必须先进行存储后面节点

           current.next = pre //断开节点,将其指向前驱实现反转的核心

           pre = current //移动当前节点位置,因为下次操作是以下一个节点开始,所以当前位置就成为了下次操作的 前驱
           current = next  //当前节点 换到下个位置,循环继续操作直至边界

    }

    return pre //循环结束pre就是反转的
   
   
}
module.exports = {
    ReverseList : ReverseList
};
/*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 = last_item,所以phead 此时是倒数第二个元素,phead.next就是最后一个元素,那么将最后一个元素.next指向其前一个元素实现反转,就是phead.next.next = phead    
   
   pHead.next = null //原来的倒数第二个元素的next指针就要清除

   return newhead//返回反转链表
}
module.exports = {
    ReverseList : ReverseList
};

你可能感兴趣的:(链表,算法,数据结构,javascript)