1. 程式人生 > >遞迴控制-連結串列反轉

遞迴控制-連結串列反轉

0.目錄

1.反轉思路

2.Java程式碼實現

1.反轉思路

連結串列反轉的意思是將 1→2→3→4→5→Null 反轉為 5→4→3→2→1→Null
反轉連結串列的遞迴思路如下:
假設2345這一段連結串列能夠反轉成功,則只需將 1→2345 的指標改為 2345→1 ,然後 1→Null 即可
以此類推,即可求得反轉連結串列

2.Java程式碼實現

2.1 結點和建立連結串列的實現

結點和建立連結串列的實現同上文 遞迴控制-建立連結串列

2.2 連結串列反轉的實現

依據反轉思路實現遞迴程式碼即可,再處理size == 0

size == 1的特殊情況。

    /**
     * Reverses a linked list.
     *
     * @param head the linked list to reverse
     * @return head of the reversed linked list
     */
    public Node reverseLinkedList(Node head) {
        // size == 0
        if (head == null) {
            return null;
        }

        // size == 1
        if (head.getNext() == null) {
            return head;
        }

        Node newHead = reverseLinkedList(head.getNext());
        head.getNext().setNext(head);
        head.setNext(null);
        return newHead;
    }

優化一下:

    public Node reverseLinkedList(Node head) {
        // size == 0 or size == 1
        if (head == null || head.getNext() == null) {
            return head;
        }

        Node newHead = reverseLinkedList(head.getNext());
        head.getNext().setNext(head);
        head.setNext(null);
        return newHead;
    }

2.3 測試用例

測試程式是否正確執行:

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        LinkedListReverser reverser = new LinkedListReverser();

        Node.printLinkedList(reverser.reverseLinkedList(
            creator.createLinkedList(new ArrayList<>())));

        Node.printLinkedList(reverser.reverseLinkedList(
            creator.createLinkedList(Arrays.asList(1))));

        Node.printLinkedList(reverser.reverseLinkedList(
            creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5))));
    }

執行結果為

main所在java檔案全部程式碼:

import java.util.ArrayList;
import java.util.Arrays;

public class LinkedListReverser {

    /**
     * Reverses a linked list.
     *
     * @param head the linked list to reverse
     * @return head of the reversed linked list
     */
    public Node reverseLinkedList(Node head) {
        // size == 0 or size == 1
        if (head == null || head.getNext() == null) {
            return head;
        }

        Node newHead = reverseLinkedList(head.getNext());
        head.getNext().setNext(head);
        head.setNext(null);
        return newHead;
    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        LinkedListReverser reverser = new LinkedListReverser();

        Node.printLinkedList(reverser.reverseLinkedList(
            creator.createLinkedList(new ArrayList<>())));

        Node.printLinkedList(reverser.reverseLinkedList(
            creator.createLinkedList(Arrays.asList(1))));

        Node.printLinkedList(reverser.reverseLinkedList(
            creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5))));
    }
}