Java单链表递归逆置

核心代码

public static void ReverseNode(Node node,Node pre){

		if(node==null) return;
		Node next=node.next;
		node.next=pre;
		ReverseNode(next,node);
	}

主程序


public class Reverse{


	public static void ReverseNode(Node node,Node pre){

		if(node==null) return;
		Node next=node.next;
		node.next=pre;
		ReverseNode(next,node);
	}
	static void Print(Node node){
		System.out.println(node.val);
		if(node.next!=null)
			Print(node.next);
	}
	public static void main(String[]args){

		Node q1=new Node(1);
		Node q2=new Node(2);
		Node q3=new Node(3);
		Node q4=new Node(4);
		Node q5=new Node(5);
		q1.next=q2;
		q2.next=q3;
		q3.next=q4;
		q4.next=q5;

		ReverseNode(q1,null);
		Print(q5);
		
		
	}
}

类定义

public class Node{

	int val;
	Node next;
	Node(int val){
		this.val=val;
	}
	Node(){}
	Node(int val,Node next){
		this.val=val;
		this.next=next;
	}
	public void setNext(Node next){
		this.next=next;
	}
	Node getNext(){
		return next;
	}
}

你可能感兴趣的:(递归,Java,java,算法)