【温习】单链表递归反转

原创
2021/04/12 18:09
阅读数 82
public class Node {
    private String name = null;
    private Node next = null;
    public Node(String name,Node next){
        this.name = name;
        this.next=next;
    }
    //递归反转节点
    public Node reverse(Node head){
        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;
    }
    //打印所有依赖节点的名字
    public void print(){
            Node curr = this;
            do{
                System.out.print(curr.name+" >> ");
                curr = curr.next;
            }while (curr!=null);
    }

    public static void main(String[] args) {
        Node nodeC = new Node("C",null);
        Node nodeB = new Node("B",nodeC);
        Node nodeA = new Node("A",nodeB);

        System.out.println(nodeA.getNodeAllName());

        //反转A节点
        Node reversedNode = nodeA.reverse(nodeA);
        reversedNode.print();
    }
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部