在这里我将使用外部类和内部类两种方法来实现java的链表,参考了java老师上课讲过的代码~
主要思想是:首先要有一个Node类(节点类),其成员变量为String 类型的name,还有一个Node类型的next,作为指向下一个节点的指针;然后会设计增删查改四个方法(addNode()、printNode()、searchNode()还有deleteNode() 这里作简写~)。然后是一个LinkList类,它首先会有一个根节点(Node 类型的root),然后是增删查改四个方法,不要忘了还有创建根节点的方法~
(⊙o⊙)…很不友好,因为我没怎么写注释。具体的代码如下(已调通):
class LinkList {
class Node{
private String name;
private Node next;
public Node(String name){
this.name=name;
}
public String getName(){
return this.name;
}
//to add a node
public void addNode(Node newNode){
if(this.next==null){
this.next=newNode;
}else{
this.next.addNode(newNode);//recursive call.it'll keep searching until finding a Node which doesn't have next node
}
}
//to print these nodes
public void printNode(){
System.out.print(this.name+"-->");
if(this.next!=null){
this.next.printNode();
}
}
//searching for a node
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;
}
}
}
//to dele