js实现反转链表的两种方法

1、反转整个链表

a.递归实现

function ListNode(val, next) {
        this.val = (val===undefined ? 0 : val)
        this.next = (next===undefined ? null : next)
     }
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head){
    // 只存在一个头节点返回本身
    if(head == null || head.next == null){
        return head;
    }
    // 进行反转
    // 递归实现
    var res = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return res;
}

b.迭代实现

var reverseList = function(head) {
    // 使用迭代实现
    let prev = null;
    let curr = head;
    while(curr){
    const next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
    }
    return prev
};

你可能感兴趣的:(javascript,链表,前端)