/*
* 結點類
*/
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.