/*
* 结点类
*/
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 ;