Java單鏈表反轉


鏈表是一種物理存儲單元上非連續、非順序的存儲結構,數據元素的邏輯順序是通過鏈表中的指針鏈接次序實現的。鏈表由一系列結點(鏈表中每一個元素稱為結點)組成,結點可以在運行時動態生成。每個結點包括兩個部分:一個是存儲數據元素的數據域,另一個是存儲下一個結點地址的指針域。 相比於線性表順序結構,操作復雜。由於不必須按順序存儲,鏈表在插入的時候可以達到O(1)的復雜度,比另一種線性表順序表快得多,但是查找一個節點或者訪問特定編號的節點則需要O(n)的時間,而線性表和順序表相應的時間復雜度分別是O(logn)和O(1)。

這篇文章主要記錄一下單鏈表反轉

v定義鏈表

/**
 * @author toutou https://www.cnblogs.com/toutou/
 * @date by 2020/11
 * @des
 */
public class ListNode {
    public int value;
    public ListNode next;

    public ListNode(int data){
        this.value = data;
    }
}

v遞歸實現

/**
 * @author toutou https://www.cnblogs.com/toutou/
 * @date by 2020/11
 * @des
 */
public class ReverseHelper {
    public static ListNode reverse(ListNode curr){
        if(curr == null || curr.next == null){
            return curr;
        }

        ListNode temp = curr.next;
        ListNode newNode = reverse(curr.next);
        temp.next = curr;
        curr.next = null;
        return newNode;
    }
}

v非遞歸實現

/**
 * @author toutou https://www.cnblogs.com/toutou/
 * @date by 2020/11
 * @des
 */
public class ReverseHelper {
    public static ListNode whileReverse(ListNode curr){
        ListNode pre = null;
        ListNode next = null;
        while(curr != null){
            next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }

        return pre;
    }
}

v測試效果

/**
 * @author toutou https://www.cnblogs.com/toutou/
 * @date by 2020/11
 * @des
 */
public class App {
    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        ListNode tmp = null;
        ListNode cur = null;
        for (int i = 1; i < 10; i++) {
            tmp = new ListNode(i);
            if (1 == i) {
                head.next = tmp;
            } else {
                cur.next = tmp;
            }
            cur = tmp;
        }

        // ListNode node1 =ReverseHelper.whileReverse(head);
        ListNode node1 =ReverseHelper.reverse(head);
        while (node1!= null){
            System.out.println(node1.value);
            node1 = node1.next;
        }

        System.out.println("OK");
    }
}

v源碼地址

https://github.com/toutouge/javademosecond/tree/master/hellospringboot


作  者:請叫我頭頭哥
出  處:http://www.cnblogs.com/toutou/
關於作者:專注於基礎平台的項目開發。如有問題或建議,請多多賜教!
版權聲明:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。
特此聲明:所有評論和私信都會在第一時間回復。也歡迎園子的大大們指正錯誤,共同進步。或者直接私信
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角推薦一下。您的鼓勵是作者堅持原創和持續寫作的最大動力!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM