前端数据结构之反转链表

94 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第5天,点击查看活动详情

反转链表

    如当输入链表{1,2,3}时,经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
    
function ReverseList(pHead)
{ 
      if(pHead == null|| pHead.next == null){
        return pHead;
      }
        let provious = null, after = null;
        // 1.改变next属性为之前元素   pHead.next = provious
        // 2.结束后改变当前pHead为之后元素,即之前的next属性 pHead = after;
        while(pHead) {
             = pHead.next;
            pHead.next = provious;
            provious = pHead;
            pHead = after;
        }
        // 末尾
        return provious;

}
module.exports = {
    ReverseList : ReverseList
};