zoukankan      html  css  js  c++  java
  • [Algorithm] 206. Reverse Linked List

    Reverse a singly linked list.

    Example:

    Input: 1->2->3->4->5->NULL
    Output: 5->4->3->2->1->NULL
    

    Follow up:

    A linked list can be reversed either iteratively or recursively. Could you implement both?

    Approach #1 (Iterative) [Accepted]

    Assume that we have linked list 1 → 2 → 3 → Ø, we would like to change it to Ø ← 1 ← 2 ← 3.

    While you are traversing the list, change the current node's next pointer to point to its previous element. Since a node does not have reference to its previous node, you must store its previous element beforehand. You also need another pointer to store the next node before changing the reference. Do not forget to return the new head reference at the end!

    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }
    

    Complexity analysis

    • Time complexity : O(n)O(n). Assume that nn is the list's length, the time complexity is O(n)O(n).

    • Space complexity : O(1)O(1).

    Approach #2 (Recursive) [Accepted]

    The recursive version is slightly trickier and the key is to work backwards. Assume that the rest of the list had already been reversed, now how do I reverse the front part? Let's assume the list is: n1 → … → nk-1 → nk → nk+1 → … → nm → Ø

    Assume from node nk+1 to nm had been reversed and you are at node nk.

    n1 → … → nk-1 → nk → nk+1 ← … ← nm

    We want nk+1’s next node to point to nk.

    So,

    nk.next.next = nk;

    Be very careful that n1's next must point to Ø. If you forget about this, your linked list has a cycle in it. This bug could be caught if you test your code with a linked list of size 2.

    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
    

    Complexity analysis

    • Time complexity : O(n)O(n). Assume that nn is the list's length, the time complexity is O(n)O(n).

    • Space complexity : O(n)O(n). The extra space comes from implicit stack space due to recursion. The recursion could go up to nn levels deep.

  • 相关阅读:
    单目标遗传算法 精英保留策略
    单目标优化问题 常用的 测试函数(MATLAB版)
    单目标优化问题 常用的 测试函数
    叼丝装备之服装必备----111111111111111111111111111111111
    算法优化之车牌识别---车牌识别优化项
    医疗器械与图像处理行业简介
    图像处理之增强---高斯模糊
    图像增强之拉普拉斯锐化---高斯一阶导二阶导数
    图像特效之油画---类似油画效果
    图像出增强之锐化---拉普拉斯锐化
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12000118.html
Copyright © 2011-2022 走看看