递归实现单链表的反转(Java实现)

要求很简单,输入一个链表,反转链表后,输出新链表的表头

递归的大致过程,就是从链表最后一个结点开始,依次回溯到head头结点,实现翻转

大致步骤如下

递归实现单链表反转

首先第一步,创建一个结点类

class Node{
    public int id;
    public Node next;

    public Node(int id){
        this.id=id;
    }
}

然后开始编写反转方法,此处以 head->1->2 链表举例

public Node reverse(Node head){
        /*
        LinkedList:  head->1->2
        1> 第一层递归
           temp=head.next (temp=1)
           newHead=reverse(1)

        2> 第二层递归
           temp=head.next (temp=2)
           newHead=reverse(2) 返回2
           2.next=head (1)  后面的结点的next等于前面的结点
           head.next=null    删除前面结点的指向
           return newHead (2)

        3> 回到第一层递归
           newHead=2
           1.next=head    后面的结点的next等于前面的结点
           head.next=null    删除前面结点的指向
           return newHead  此时的newHead为新的头结点
         */
        if (head==null || head.next==null){
            return head;
        }
        Node temp=head.next;
        Node newHead=reverse(head.next);
        temp.next=head;
        head.next=null;
        return newHead;
    }

猜你喜欢

转载自blog.csdn.net/u013523775/article/details/105078533