java 链表

//单向链表!
class Link{
	class Node{
		private String name;//保存节点的名字
		private Node next;//保存下一个节点!
		public Node(String name) {
			this.name = name;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public void addNode(Node newNode){
			if(this.next==null){//后面没有东西了!
				this.next=newNode;
			}else{
				this.next.addNode(newNode);//继续向下查!
			}
		}
		public void printNode(){
			System.out.print(this.name+"-->");
			if(this.next!=null){
				this.next.printNode();//向下继续列出!
			}
		}
		public boolean searchNode(String name){
			if(this.name.equals(name)){
				return true;
			}else{
				if(this.next!=null){
					return this.next.searchNode(name);
				}else{
					return false;
				}
				
			}
		}
		public void deleteNode(Node preNode,String name){
			if(this.name.equals(name)){
				System.out.println("*************name="+name+"************");
				preNode.next=this.next;
			}else{
				this.next.deleteNode(this,name);
			}
		}
	}
	private Node root;//定义出根节点!
	public void add(String name){
		Node newNode=new Node(name);
		if(root==null){ //没有根节点!
			this.root=newNode;
		}else{
			this.root.addNode(newNode);
		}
	}
	public void print(){
		if(this.root!=null){
			this.root.printNode();
		}
	}
	public boolean search(String name){
		if(this.root!=null){
			return this.root.searchNode(name);
		}else{
			return false;
		}
	}
	public void delete(String name){
		if(this.search(name)){//判断该删除的节点是否存在!
			if(this.root.name.equals(name)){
				if(this.root.next!=null){
					 this.root=this.root.next;//改变根节点!
				 }else{
					 this.root=null;
				 }
			}else{
				if(this.root.next!=null){
					this.root.next.deleteNode(root, name);
				}
			}
		}else{
			System.out.println("none");
		}
	}
}
public class LinkDemo {
	public static void main(String[] args) {
		Link link=new Link();
		link.add("Num1");
		link.add("Num2");
		link.add("Num3");
		link.add("Num4");
		link.print();
		System.out.println();
		link.delete("Num4");
		link.print();
		System.out.println();
		link.delete("Num1");
		link.print();
	}
}

猜你喜欢

转载自blog.csdn.net/YAREI/article/details/17059631