一直对链表不太熟悉, 今天看了下并写了下来, 错的地方请指正.(注意:有的地方判断不够严格).
package com.test;
public class Link {
Node root;
private class Node{
String name ;
Node next;
public Node(String name){
this.name = name;
}
public void add(Node node) {
if(this.next == null){
this.next = node;
}else{
this.next.add(node);
}
}
public void print() {
System.out.print(this.name+"--->");
if(this.next != null){
this.next.print();
}
}
public boolean query(String name) {
if(this.next == null){
return false;
}else if(this.next.name.equals(name)){
return true;
}else{
return this.next.query(name);
}
}
public void delete(Node preNode , String name) {
if(this.name.equals(name)){
preNode.next = this.next;
}else{
this.next.delete(this , name);
}
}
}
public void addNode(String name){
if(this.root == null){
this.root = new Node(name);
}else {
this.root.add(new Node(name));
}
}
public boolean queryNode(String name){
if(this.root == null){
return false;
}else if(this.root.name.equals(name)){
return true;
}else{
return this.root.query(name);
}
}
public void deleteNode(String name){
if(this.root != null){
if(this.root.name.equals(name)){
this.root = this.root.next;
}else{
this.root.next.delete(root,name);
}
}
}
public static void main(String[] args) {
Link link = new Link();
link.addNode("根");
link.addNode("1");
link.addNode("2");
link.addNode("3");
link.addNode("4");
link.print();
System.out.println("");
System.out.println(link.queryNode("1"));
System.out.println("");
link.deleteNode("2");
link.print();
}
void print(){
if(this.root != null){
this.root.print();
}
}
}