java实现单链表

来源:互联网 发布:linkdeque java 编辑:程序博客网 时间:2024/06/15 08:08

public class LinearList {
static class NodeManager{
private Node root;
//添加节点
public void addNode(String name){
if(root==null){
root=new Node(name);
}else {
root.add(name);
}
}
//删除节点
public void deleteNode(String name){
if(root!=null){
if(root.name.equals(name)){
root=root.next;
}else{
root.dele(name);
}
}
}
//打印节点
public void printNode(){
if(root!=null){
System.out.println(root.name);
root.print();
}
}
//内部类Node
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 dele(String name){
if(this.next!=null){
if(this.next.name.equals(name)){
this.next=this.next.next;
}else{
this.next.dele(name);
}
}
}
//打印链表
public void print(){
if(this.next!=null){
System.out.println(this.next.name);
this.next.print();
}
}
 }

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


}


}

0 0
原创粉丝点击