zoukankan      html  css  js  c++  java
  • [LeetCode] Reverse Linked List

    Reverse a singly linked list.

    这题因为palindrome linked list 的时候需要就顺便做了一下。利用三个指针:prev, now, next 相互倒腾就行。

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var reverseList = function(head) {
        if (!head) return null;
        var prev = null;
        var now = head;
        var next = head.next
        
        while (now) {
            now.next = prev;
            prev = now;
            now = next;
            if (next) next = next.next;
        }
        return prev;
    };

    还可以递归的解决。算法2:

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
     var reverseHelp = function(head) {
         if (!head.next) return head;
         reverseHelp(head.next).next = head;
         return head;
     }
     
    var reverseList = function(head) {
        if (!head) return null;
        var tail = head;
        while (tail.next) {
            tail = tail.next;
        }
        
        reverseHelp(head).next = null;
        return tail;
    };

    但是问题是翻转以后,原来的尾巴变成了头,我没有想到太好的递归方法,就先遍历了一遍找到尾,然后再用递归的翻转head。

    第一次提交的时候出现了bug,原因是递归过程 reverseHelp 是返回链表尾,所以最后别忘了把他最终返回的链表尾巴.next = null;

  • 相关阅读:
    POJ 1006 ( 中国剩余定理 )
    HDU 2736 Surprising Strings
    STL----map 章节
    最短路问题
    [HAOI2007]反素数
    严格次小生成树[BJWC2010]
    P3320 [SDOI2015]寻宝游戏(LCA)
    [Violet]樱花/阶乘分解
    [HNOI2008]GT考试
    2012 年国家集训队互测 Tree
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4908120.html
Copyright © 2011-2022 走看看