java单链表的实现

package com.struct;

public class LinkListDemo {

	public static void main(String[] args){
		NodeManager nm = new NodeManager();
		nm.addNode("节点1");
		nm.addNode("节点2");
		nm.addNode("节点3");
		nm.addNode("节点4");
		nm.addNode("节点5");
		nm.printNode();
		nm.delNode("节点5");
		nm.printNode();
		
	}

}
class NodeManager{
	//根节点
	private Node root;
	/**
	 * 添加节点
	 * @param name
	 */
	public void addNode(String name){
		if(root == null)
			root = new Node(name);
		else{
			root.add(name);
		}
			
		
	}
	//删除节点
	public void delNode(String name){
		if(root != null){
			if(root.name.equals(name))
				root = root.next;
			else{
				root.del(name);
			}
		}
	}
	//删除节点
	public void printNode(){
		if(root !=null){
			System.out.print(root.name);
			root.print();
			System.out.println();
		}
	}
	//定义一个节点类
	class Node{
		private String name;
		//表示下一个节点对象
		private Node next;
		public Node(String name){
			this.name = name;
		}
		public void add(String name){
			if(this.next == null){
				this.next = new Node(name);
			}
			else{
				this.next.add(name);
			}
		}
		public void del(String name){
			if(this.next != null){
				if(this.next.name.equals(name)){
					this.next = this.next.next;
				}else{
					this.next.del(name);
				}
			}
		}
		//输出所以节点
		public void print(){
			if(this.next != null){
				System.out.print("-->" + this.next.name);
				this.next.print();
			}
		}
	}
}
输出:
节点1-->节点2-->节点3-->节点4-->节点5
节点1-->节点2-->节点3-->节点4
 

你可能感兴趣的:(java单链表的实现)