Created
September 6, 2014 03:35
-
-
Save mushishizh/5770e0e9790a90becc3c to your computer and use it in GitHub Desktop.
What is a little bit tricky is that no matter which node is deleted, actually only the first node is deleted......
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package testdemo01; | |
class Link{ | |
class Node{ | |
private String name; | |
private Node next; | |
public Node(String name){ | |
this.name = name; | |
} | |
public String getName(){ | |
return this.name; | |
} | |
public void addNode(Node newNode){ | |
if(this.next == null){ | |
this.next = newNode; | |
}else{ | |
this.next.addNode(newNode); | |
} | |
} | |
public void printNode(){ | |
System.out.println(this.name+",,,,,"); | |
if(this.next!=null){ | |
this.next.printNode(); | |
} | |
} | |
public boolean searchNode(String name){ | |
if(this.name == name){ | |
return true; | |
}else{ | |
if(this.next!=null){ | |
return this.next.searchNode(name); | |
}else{ | |
return false; | |
} | |
} | |
} | |
public void deleteNode(Node preNode, String name2){ | |
if(this.name.equals(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(this.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 name1){ | |
if(this.search(name1)){ | |
if(this.root.name.equals(name1)){ | |
if(this.root.next!=null){ | |
this.root = this.root.next; | |
}else{ | |
this.root = null; | |
} | |
}else{ | |
if(this.root.next!=null){ | |
this.root.next.deleteNode(this.root, name1); | |
} | |
} | |
} | |
} | |
}; | |
public class TestDemo01 { | |
public static void main(String[] args){ | |
Link link = new Link(); | |
link.add("root"); | |
link.add("first"); | |
link.add("second"); | |
link.add("third"); | |
link.add("four"); | |
link.add("five"); | |
link.print(); | |
System.out.println(link.search("x")); | |
link.delete("fi"); | |
link.print(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment