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;

  • 相关阅读:
    “孤立”用户
    MongoDB 维护Replica Set
    Design7:数据删除设计
    abap取中值的函数
    REPLACE...IN.....WITH.... 的使用
    ABAP中RETURN与EXIT语句的区别
    在一个程序中调用另一个程序并且传输数据到选择屏幕执行这个程序
    Extract Datasets
    事件
    计算字符串长度的实例
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4908120.html
Copyright © 2011-2022 走看看