java的单向链表_Java实现单向链表

/*

* 结点类

*/

public class Node {

private int data;

private Node next;

public Node(int data) {

this.data = data;

this.next = null;

}

// 设置结点 数据的方法

public void setData(int data) {

this.data = data;

}

// 设置结点指针的方法

public void setNext(Node next) {

this.next = next;

}

// 获取结点数据的方法

public int getData() {

return this.data;

}

// 获取下一个结点的方法

public Node getNext() {

return this.next;

}

}

/*

* 单向链表类

*/

public class List{

private Node head;

public List() {

this.head = null;

}

// 链表尾部添加结点

public void addNode(Node node) {

if (head == null) {

head = node;

}

else {

Node tmp = head;

while(tmp.getNext() != null) {

tmp = tmp.getNext();

}

tmp.setNext(node);

}

}

// 删除结点

public void deleteNode(Node node) {

if (!isExist(node)) {

System.out.println("结点不存在!");

return ;

}

if (this.head.getData() == node.getData()) {

this.head = this.head.getNext();

return ;

}

Node tmp = this.head;

while (tmp != null) {

if (tmp.getNext().getData() == node.getData())

break;

tmp = tmp.getNext();

}

tmp.setNext(tmp.getNext().getNext());

}

// 遍历链表

public void traverse() {

if (this.head == null) {

System.out.println("链表为空");

return ;

}

System.out.print("链表各结点为:");

Node tmp = head;

while (tmp != null) {

System.out.print(tmp.getData() + " ");

tmp = tmp.getNext();

}

System.out.println();

}

// 判断结点是否存在

boolean isExist(Node node) {

Node tmp = head;

while (tmp != null) {

if (tmp.getData() == node.getData())

return true;

tmp = tmp.getNext();

}

return false;

}

}

public class TestList {  public static void main(String[] args) {   // TODO Auto-generated method stub //  实例化链表类,添加10个结点   List list = new List();   for (int i=0; i<10; i++) {    list.addNode(new Node(i+1));   } //  遍历链表   list.traverse(); //  删除其中一个结点   list.deleteNode(new Node(5)); //  删除后再次遍历链表   list.traverse();  } }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值