java代码实现链表_java单链表代码实现
用慣了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的單鏈表實現核心在于多層次迭代。
原文:http://blog.csdn.net/u014492609/article/details/42809181
總結
以上是生活随笔為你收集整理的java代码实现链表_java单链表代码实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 风疹的症状怎么治疗
- 下一篇: java短信接口 调用_带你了解短信接口