用惯了C++,java写起来果然不太爽。。。不废话了,上代码。。。
package javaInnerclassDemo;
class Link{
class Node{
private String name;
private Node next;
public Node(String name){
this.name=name;
}
public void setname(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(){
if(this.next!=null){
System.out.print(this.name);
System.out.print("——>");
}
else
System.out.println(this.name);
if(this.next!=null)
this.next.printnode();
}
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 ;
}
}
}
public void deleteNode(Node preNode,String name){
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){ //之所以在外部判断,因为printnode需要迭代
this.root.printnode();
}
else
System.out.println("链表为空,无法打印!");
}
public boolean search(String name){
if(this.root.searchnode(name)==true)
return true;
else
return false;
}
public void delete(String name){
if(this.search(name)){ // 判断此节点是否存在
if(this.root.name.equals(name)){
if(this.root.next!=null){
this.root = this.root.next ; // 改变根节点
}
else{
this.root = null ; // 取消
}
}
else{
if(this.root.next!=null){
this.root.next.deleteNode(root,name) ;
}
}
}
else
System.out.println("所要删除节点不存在!");
}
}
public class LinklistDemo {
public static void main(String[] args) {
Link l = new Link();
l.add("walkthehorizon");
l.add("已经");
l.add("无人");
l.add("能挡");
l.add("了");
l.add("么");
System.out.println("打印链表");
l.print();
System.out.println("查找链表");
System.out.println(l.search("walkthehorizon"));
System.out.println(l.search("放逐之刃"));
System.out.println("删除节点");
l.delete("么");
l.print();
}
}
java的单链表实现核心在于多层次迭代。