單鏈表也是最基本的一個(gè)數(shù)據(jù)類型余掖,相對(duì)比較簡(jiǎn)單作谭。
如果有任何疑問(wèn)歡迎來(lái)探討硼讽。
首先是節(jié)點(diǎn)數(shù)據(jù)
package ListExercise;
public class Node<T> {
// 下一個(gè)節(jié)點(diǎn)
public Node<T> next;
// 任意數(shù)據(jù)類型
public T data;
// 初始化數(shù)據(jù)
public Node(T t) {
this.data = t;
next = null;
}
}
接下來(lái)是我們的核心代碼
package ListExercise;
public class LinkedList<T> {
// 頭結(jié)點(diǎn)
private Node<T> headNode;
// 鏈表長(zhǎng)度
private int size;
// -1是頭節(jié)點(diǎn)捉偏,沒(méi)有數(shù)據(jù)
public LinkedList() {
size = 0;
headNode = new Node<T>(null);
}
// 添加元素data
public boolean add(T data) {
boolean ret = false;
Node<T> node = getHide(this.size - 1);
node.next = new Node<T>(data);
size++;
ret = true;
return ret;
}
// 添加元素data
public boolean insert(int index, T data) {
boolean ret = false;
Node<T> node = getHide(index - 1);
Node<T> nextNode = node.next;
node.next = new Node<T>(data);
node.next.next = nextNode;
size++;
ret = true;
return ret;
}
// 刪除元素data
public boolean remove(T data) {
boolean ret = false;
Node<T> a = headNode;
while (a.next != null) {
if (a.next.data == data) {
a.next = a.next.next;
ret = true;
break;
}
a = a.next;
}
size--;
return ret;
}
// 刪除元素data
public boolean removeAt(int index) {
boolean ret = false;
if (index >= 0 && index < size) {
Node<T> a = headNode;
int i = -1;
while (i < index - 1) {
a = a.next;
i++;
}
size--;
a.next = a.next.next;
} else {
throw new RuntimeException("超出數(shù)據(jù)范圍:" + index);
}
return ret;
}
// -1是頭節(jié)點(diǎn),沒(méi)有數(shù)據(jù)
public Node<T> get(int index) {
if (index < 0 || index >= size) {
throw new RuntimeException("超出數(shù)據(jù)范圍:" + index);
}
return getHide(index);
}
// -1是頭節(jié)點(diǎn)农渊,沒(méi)有數(shù)據(jù)
private Node<T> getHide(int index) {
int i = -1;
Node<T> ret = headNode;
while (i < index) {
ret = ret.next;
i++;
}
return ret;
}
public void print() {
Node<T> t = headNode;
int i = 0;
while (t.next != null) {
t = t.next;
System.err.println(t.data);
i++;
if (i > 100)
break;
}
System.err.println("長(zhǎng)度為:" + i);
}
}
最后是測(cè)試的代碼:
package ListExercise;
public class Main {
public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<Integer>();
for (int i = 0; i < 10; i++) {
linkedList.add(i);
}
linkedList.print();
linkedList.insert(10,10);
linkedList.remove(1);
linkedList.removeAt(0);
linkedList.print();
}
}
最后患蹂,雙向鏈表和循環(huán)鏈表和單鏈表基本差不多就不一一舉例了。