206. 反转链表

1 迭代法反转:
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;
}

2 递归法反转:

var reverseList = function(head){
    if(head==null || head.next==null){
        return head;
    }
    // 遍历到最后一个节点
    const newHead = reverseList(head.next);
    head.next.next = head;
    head.next=null;
    return newHead;
}

 

 

posted on 2021-06-14 22:55  BillGates--  阅读(67)  评论(0)    收藏  举报