LeetCode-反轉一個單鏈表

迭代解法:

1、首先將head指向null

2、然後對next往下遍歷的同時讓他指向前一個

3、爲了保證往下指向,使用temp暫存next.next

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

遞歸解法:

將問題轉換爲讓每一個節點的指針指向他前面的節點

遞歸就是先遍歷到最後一個節點,然後讓他指向前一個節點,結束

因爲有系統棧所以他的前一個節點被保存下來,繼續遞歸的進行

也就是假設列表的其餘部分已經被反轉

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

    private ListNode reverse(ListNode node, ListNode next){
        if (next == null){
            return node;
        }
        ListNode head = reverse(node.next, next.next);
        next.next = node;
        return head;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章