您的位置:首页 > 编程语言 > Java开发

一个简单的Java单链表

2012-07-28 02:54 253 查看
一直对链表不太熟悉, 今天看了下并写了下来, 错的地方请指正.(注意:有的地方判断不够严格).

这是一个单向链表:

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();
}
}

}

打印结果:

   根--->1--->2--->3--->4--->

   true

   根--->1--->3--->4--->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 链表 单向链表