使用java实现链表。两种实现,代码分别如下:
第一种实现
第二种实现
第一种实现
package com.bmwm5gtr.test;
class Node{
private String name;
private Node next;
public Node(String name){
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next=next;
}
public static void printNode(Node node){
if(node.getNext()==null){
//是最后一个节点
System.out.print(node.getName());
}else{
System.out.print(node.getName()+"--->");
printNode(node.getNext());
}
}
}
public class Node01 {
public static void main(String[] args){
Node root=new Node("火车头");
Node r1=new Node("第一节火车");
Node r2=new Node("第二节火车");
Node r3=new Node("第三节火车");
Node r4=new Node("第四节火车");
Node end=new Node("火车尾");
root.setNext(r1);
r1.setNext(r2);
r2.setNext(r3);
r3.setNext(r4);
r4.setNext(end);
Node.printNode(root);
}
}
第二种实现
package com.bmwm5gtr.test;
class Link{
//*****内部类Start******
class Node{
private String name ; // 保存节点的名字
private Node next ; // 保存下一个节点
public Node(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(){
System.out.print(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) ;
}
}
};
//*****内部类End******
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){
this.root.printNode() ;
}
}
public boolean search(String name){ // 指定查找的名字
if(this.root!=null){
return this.root.searchNode(name) ;
}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) ;
}
}
}
}
};
public class Node02{
public static void main(String args[]){
Link link = new Link() ;
link.add("根节点") ;
link.add("第一节点") ;
link.add("第二节点") ;
link.add("第三节点") ;
link.add("第四节点") ;
link.add("第五节点") ;
link.print() ;
System.out.println("-----------------") ;
System.out.println(link.search("第x节点")) ;
link.delete("第四节点") ;
link.delete("根节点") ;
System.out.println("-----------------") ;
link.print() ;
}
};