用Java实现单向链表

【说明】
封装节点类,既用于存储数据data和下一个节点的首地址next,又封装了基本的增删改查的功能。
方便以后调用,而不用要用户手工去处理各个节点的关系。

//

class Link{
private Node root;//the head node

public void addNode(String data){
Node newNode = new Node(data);
if(this.root == null){
this.root = newNode;
}else{
this.root.add(newNode);//method add() is defined in class Node.
}
}
public void printNode(){
if(this.root != null){
this.root.print();
}
}
public boolean contains(String name){
return this.root.search(name);
}
public void deleteNode(String data){
if(this.contains(data)){
if(this.root.data.equals(data)){
this.root = this.root.next;
}else{
this.root.next.delete(root, data);
}
}
}
//inner class Node,将节点进行封装,方便以后的调用,而不用由用户手工去处理各个节点的关系。
class Node{
private String data;
private Node next;
public Node(String data){
this.data = data;
}
public void add(Node newNode){//add node but no data
if(this.next == null){
this.next = newNode;
}else{
this.next.add(newNode);//迭代的方法
}
}
public void print(){//迭代输出
System.out.println(this.data);
if(this.next != null){
this.next.print();
}
}
public boolean search(String data){
if(data.equals(this.data)){
return true;
}else{
if(this.next != null){
return this.next.search(data);
}else{
return false;
}
}
}
public void delete(Node previous, String data){//可以把previous理解为头指针
if(data.equals(this.data)){
previous.next = this.next;
}else{
if(this.next != null){
this.next.delete(this, data);
}
}
}
}


}
public class Test12_1 {
public static void main(String args[]){
Link l = new Link();
l.addNode("A");
l.addNode("B");
l.addNode("C");
System.out.println("=====================before delete================");
l.printNode();
l.deleteNode("B");
System.out.println("==================deleted==================");
l.printNode();
System.out.println();
System.out.println("searse node: "+l.contains("A"));
}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值