java简易双向链表的实现(添加和双向输出操作)

  • 节点类
    与单链表的区别主要在于添加节点时,需要指定新添加节点的前驱
class Node{//节点类
	private String name;
	private Node pervious;
	protected Node next;
	public Node(){}
	public Node(String name){this.setName(name);}
	public Node(String name,Node pervious,Node next){
		this.name=name;
		this.pervious=pervious;
		this.next=next;
	}
	public void setName(String name){this.name=name;}
	public void setPervious(Node pervious){this.pervious=pervious;}
	public void setNext(Node next){this.next=next;}
	public String getName(){return this.name;}
	public Node getNext(){return this.next;}
	public void addNode(Node newNode){//添加节点
		if(this.next==null){
			this.next=newNode;
			newNode.setPervious(this);//设置新添加节点的前驱节点
		}else{
			this.next.addNode(newNode);
		}
	}
	public void pPrintNode(){
		System.out.println("姓名:"+this.getName());
		if(this.next!=null){
			this.next.pPrintNode();
		}
	}
	public void nPrintNode(){
		System.out.println("姓名:"+this.getName());
		if(this.pervious!=null){
			this.pervious.nPrintNode();
		}
	}
}

链表类,实现双向的遍历输出

class Link{
	private static int LENGTH=0;
	private Node root;
	public Link(){}
	public void add(Node newNode){
		++LENGTH;
		if(this.root==null){
			this.root=newNode;
		}else{
			this.root.addNode(newNode);
		}
	}
	public void pPrint(){
		if(this.root==null){//从根节点由前向后输出
			System.out.println("空表");
		}
		System.out.println("从前往后输出:");
		this.root.pPrintNode();
	}
	public Node getLast(){//得到最后一个节点
		Node n=new Node();
		n=this.root;
		for(int i=1;i<LENGTH;++i){//注意下标,不要越界
			n=n.next;
		}
		return n;
	}
	public void nPrint(Node node){//从指定位置由后向前输出
		System.out.println("从后往前输出");
		node.nPrintNode();
	}
}

测试类

public class Train{
	public static void main(String args[]){
		Node n1=new Node("张三");
		Node n2=new Node("李四");
		Node n3=new Node("王五");
		Node n4=new Node("赵六");
		Node n5=new Node("孙七");
		Link l=new Link();
		l.add(n1);
		l.add(n2);
		l.add(n3);
		l.add(n4);
		l.add(n5);
		l.pPrint();
		System.out.println();
		l.nPrint(l.getLast());
	}
}

运行结果

©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页