美文网首页
206. 反转链表

206. 反转链表

作者: Jason_Shu | 来源:发表于2019-02-26 15:10 被阅读0次

题目链接:https://leetcode-cn.com/problems/reverse-linked-list/

思路:用三个指针依次指向null,head和head.next,然后反转指针指向。

var reverseList = function(head) {
    if(head === null || head.next === null) {
        return head;
    }
    
    let p = head;
    let q = head.next;
    let k = null;
    
    while(q !== null) {
        p.next = k;
        k = p;
        p = q;
        q = q.next;
    }
    
    // 最后要把最后一个节点反转到倒数第二个节点
    p.next = k;
    
    return p;
};

相关文章

网友评论

      本文标题:206. 反转链表

      本文链接:https://www.haomeiwen.com/subject/zibayqtx.html