递归控制-链表反转

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 == 0size == 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))));
    }
}
posted @ 2018-11-24 20:11  PyLearn  阅读(509)  评论(0编辑  收藏  举报