LeetCode——第206題:反轉鏈表

題目:

反轉一個單鏈表。

示例:

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

進階:

你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?

代碼:

package leetCode;

import leetCode.Nineteen.ListNode;

/**
 * 2018.7.23
 * 反轉鏈表
 * 思路1:感覺可以先掃描一遍鏈表將值存到一個數組,在循環數組得出一個反轉鏈表
 * 思路2:感覺可以在掃描的同時以從鏈表頭的方式插入結點完成鏈表反轉
 * 進階思路:遞歸或迭代
 * @author dhc
 *
 */
public class TwoHundredAndSix {
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
    //採用思路2(當用註釋的re是,是36ms,後來發現並不用這個re直接用head就行,直接0.5ms,有毒)
    public static ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        }
        //ListNode re = head;
        ListNode loopNode = head.next;
        head.next = null;
        while(loopNode != null) {
            ListNode tem = head;
            head = loopNode;
            loopNode = loopNode.next;
            head.next = tem;
        }
        return head;
    }
    //採用遞歸方法(大佬答案,不是很好理解的樣子)
    public static ListNode reverseList1(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode sub = reverseList(head.next);
        //讓後面一個結點指向前一個結點,遞歸的話是從最後一個結點開始,一直到最開始的結點
        head.next.next = head;
        //如果不只爲空的話,head.next==head.next.next,而head.next.next=head,最後形成一個環
        head.next = null;
        return sub;
    }
    public static void main(String[] args) {
        ListNode head = new TwoHundredAndSix().new ListNode(1);
        ListNode node1 = new TwoHundredAndSix().new ListNode(2);
        ListNode node2 = new TwoHundredAndSix().new ListNode(3);
        ListNode node3 = new TwoHundredAndSix().new ListNode(4);
        ListNode node4 = new TwoHundredAndSix().new ListNode(5);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        ListNode re = reverseList1(head);
        while(re!=null) {
            if(re.next == null) {
                System.out.print(re.val);
            }else {
                System.out.print(re.val+"->");
            }
            re = re.next;
        }
    }
}
發佈了75 篇原創文章 · 獲贊 13 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章