链表

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;
}

 

 

上一篇:jmeter断言


下一篇:27. 移除元素