xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js algorithm reverse linked list All In One

js algorithm reverse linked list All In One

reverse linked list / 反转链表

function ListNode(val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}

const head = new ListNode(1, 2); 
head.next = new ListNode(2, 3); 


// 递归
var reverseList = function(head) {
    if (head == null || head.next == null) {
        return head;
    }
    let temp = head.next;
    let newHead = reverseList(temp);
    temp.next = head;
    head.next = null;
    return newHead;
};

// 迭代
var reverseList = function(head) {
    let newHead = new ListNode();
    while(head) {
       let temp = head.next;
       head.next = newHead.next;
       newHead.next = head;
       head = temp;
    }
    return newHead.next;
};

const newHead = reverseList(head);

https://leetcode.com/problems/reverse-linked-list/description/

interview

python

refs

https://www.cnblogs.com/xgqfrms/tag/Algorithm/



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-10-07 08:59  xgqfrms  阅读(41)  评论(3编辑  收藏  举报