逆轉單向鏈表看這一篇就夠了【JAVA】


逆轉單向鏈表

逆轉前: 1 -> 2 -> 3 -> 4 -> 5 -> null

逆轉后: 5 -> 4 -> 3 -> 2 -> 1 -> null

個人博客地址:逆轉單向鏈表

方法一、循環迭代

image

public Node reverse(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        // 取前面節點
        Node pre = head;
        // 取后面節點
        Node cur = head.next;
        // 臨時節點
        Node temp = null;
        while (cur != null) {
            // 1. 保存后節點的指向節點 因為要替換后節點的指向節點為他的前節點
            temp = cur.next;
            // 2. 把后節點的指向的節點替換成前節點
            cur.next = pre;
            // 下一輪要替換的前節點和后節點
            // 第一次 pre = 1 cur =2  || 那第二次 就得 pre = 2 cur = 3
            pre = cur;
            cur = temp;
        }
        // 在上述過程中未替換首節點的指向節點 這里首節點將成為尾節點 所以指向null
        head.next = null;
        // 因為循環的條件是cur是否為null 如果cur為null 那 pre將是原來鏈表的尾節點
        // 就是逆轉后的首節點
        return cur;
    }

方法二:遞歸

public Node recursionNode(Node head) {
         if (head == null || head.next == null) {
            return head;
        }
        // head 1 2 3 4
        Node node = reverseNode(head.next);
        // 展示順序 head 4 3 2 1

        // 第一輪:
        // 當前指向順序 4 -> 5 
        
        head.next.next = head; // 變成了 5 -> 4 但是4的指針仍然指向5 也就是雙向的
        // 所以 4 -> null 變成單向
        head.next = null;
        
        // node是最后一個元素 5 也就是逆轉后的 第一個元素
        return node;
    }

更多文章查看個人博客 個人博客地址:逆轉單向鏈表


免責聲明!

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



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