Java 實現自定義鏈表
節點類 Node.java
public class Node {
/** 當前節點的數據*/
private String data;
/** 如果當前節點是首/尾節點 NULL 或者是 下一個節點的實例*/
private Node next;
public Node(final String data) {
this.data = data;
}
public void setNext(final Node next) {
this.next = next;
}
public Node getNext() {
return this.next;
}
public String getData() {
return this.data;
}
public void addNode(final Node newNode) {
if (this.next == null) {
this.next = newNode;
} else {
this.next.addNode(newNode);
}
}
public void printNode() {
System.out.println(this.data);
if (this.next != null) {
this.next.printNode();
}
}
public boolean containNode(final String data) {
/** 比對當前節點數據是否相同*/
if (this.data.equals(data)) {
return true;
} else {
if (this.next != null) {
return this.next.containNode(data);
} else {
return false;
}
}
}
public void removeNode(final Node previous, final String data) {
/** 比對當前節點數據是否和將要刪除的數據相同*/
if (this.data.equals(data)) {
/** 數據相同的前提下 把下一個節點覆蓋到上一個節點的 next*/
previous.next = this.next;
} else {
this.next.removeNode(this, data);
}
}
}
操作功能類 Link.java
public class Link {
private Node root;
public void add(final String data) {
if (data == null || this.contains(data)) {
return;
}
Node newNode = new Node(data);
if (this.root == null) {
this.root = newNode;
} else {
this.root.addNode(newNode);
}
}
public void print() {
if (this.root != null) {
this.root.printNode();
}
}
public boolean contains(final String data) {
if (data == null || this.root == null) {
return false;
}
return this.root.containNode(data);
}
public void remove(final String data) {
/** 1. 首先判斷是否有相同數據節點*/
if (this.contains(data)) {
/** 2. 將要刪除的數據和當前根節點數據節點相同的話 把下一個節點覆蓋到根節點*/
if (this.root.getData().equals(data)) {
this.root = this.root.getNext();
} else {
/** 通過當前根節點和將要刪除的數據, 刪除節點*/
this.root.getNext().removeNode(this.root , data);
}
}
}
}
App.java
public class App {
public static void main(String[] args) {
final Link list = new Link();
list.add("饅頭");
list.add("豆漿");
list.add("茶葉蛋");
list.add("包子");
list.add("麻花");
list.add("豆漿");
/** 刪除*/
list.remove("包子");
list.remove("豆漿");
/** 打印*/
list.print();
/** 查詢*/
System.out.println(list.contains("饅頭"));
System.out.println(list.contains("豆漿"));
}
}
結果:
> 饅頭
> 茶葉蛋
> 麻花
> true
> false
如果您覺得有幫助,歡迎點贊哦 ~ 謝謝!!