1. 程式人生 > >C#LeetCode刷題之#206-反轉連結串列(Reverse Linked List)

C#LeetCode刷題之#206-反轉連結串列(Reverse Linked List)

問題

反轉一個單鏈表。

輸入: 1->2->3->4->5->NULL輸出: 5->4->3->2->1->NULL

進階: 你可以迭代或遞迴地反轉連結串列。你能否用兩種方法解決這道題?

Reverse a singly linked list.

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?

示例

public class Program {

    public static void Main(string[] args) {
        var head = new ListNode(1) {
            next = new ListNode(2) {
                next = new ListNode(3) {
                    next = new ListNode(4) {
                        next = new ListNode(5)
                    }
                }
            }
        };

        var res = ReverseList(head);
        ShowArray(res);

        head = new ListNode(10) {
            next = new ListNode(7) {
                next = new ListNode(23) {
                    next = new ListNode(86) {
                        next = new ListNode(56)
                    }
                }
            }
        };

        res = ReverseList2(head);
        ShowArray(res);

        Console.ReadKey();
    }

    private static void ShowArray(ListNode list) {
        var node = list;
        while(node != null) {
            Console.Write($"{node.val} ");
            node = node.next;
        }
        Console.WriteLine();
    }

    private static ListNode ReverseList(ListNode head) {
        var node = head;
        ListNode pre = null;
        while(node != null) {
            var temp = node.next;
            node.next = pre;
            pre = node;
            node = temp;
        }
        return pre;
    }

    private static ListNode ReverseList2(ListNode head) {
        if(head == null || head.next == null) return head;
        var result = ReverseList2(head.next);
        head.next.next = head;
        head.next = null;
        return result;
    }

    public class ListNode {
        public int val;
        public ListNode next;
        public ListNode(int x) { val = x; }
    }

}

以上給出2種演算法實現,以下是這個案例的輸出結果:

5 4 3 2 1
56 86 23 7 10

分析:

顯而易見,以上2種演算法的時間複雜度均為: O(n) 。