叮咚~单向链 反向

package test.collections;

public class Node {

	public String name;
	public Node nextNode;
	public Node(String name){
		this.name = name;
		this.frist = this;
	}
	public Node frist =null;
	
	
	public static Node revers(Node node){
		node.frist = null;
		node.rever(node);
		return node.frist;
	}
	
	public Node rever(Node node){
		if(node.nextNode==null){
			frist = node;
			return frist;
		}
		Node next = rever(node.nextNode);
		
		next.nextNode=node;
	        node.nextNode=null;
		return node;
	}
	
	
	public String toString(){
		if(this.nextNode!=null){
			return this.name + this.nextNode.toString();
		}
		return this.name; 
	}
	
	
	
	
	public static void main(String[] args){
		Node node = new Node("n1");
		node.nextNode=new Node("n2");
		node.nextNode.nextNode = new Node("n3");
		node.nextNode.nextNode.nextNode = new Node("n4");
		System.out.println(node);
		System.out.println(Node.revers(node));
		
	}
	
}

你可能感兴趣的:(反向)