java實現雙向連結串列(帶啞結點)
阿新 • • 發佈:2021-01-12
技術標籤:java
雙向連結串列雙鏈表,是連結串列的一種,它的每個資料結點中都有兩個指標,分別指向直接後繼和直接前驅。
package cn.tnt.test;
/**
* @Author TNT-df
* @Date 2021/1/10 15:05
* @Description
*/
public class DoubleLinedList {
Node head = new Node();
Node tail = new Node();
public DoubleLinedList() {
}
//頭插
public void addFirst (int val) {
Node node = new Node(val);
if (head.next == null) {
node.next = tail;
tail.prev = node;
} else {
node.next = head.next;
head.next.prev = node;
}
head.next = node;
node.prev = head;
}
//尾插
public void addLast(int val) {
Node node = new Node(val);
if (head.next == null) {
node.next = tail;
tail.prev = node;
head.next = node;
node.prev = head;
} else {
node.next = tail;
node.prev = tail.prev;
tail. prev.next = node;
tail.prev = node;
}
}
//在指定下標處插入
public void addIdx(int index, int key) {
if (contians(key) && (index > 0 && index < getLength())) {
Node node = new Node(key);
Node cur = head.next;
for (int i = 1; i <= index - 1; i++) {
cur = cur.next;
}
node.next = cur.next;
cur.next.prev = node;
cur.next = node;
node.prev = cur;
}
}
//是否包含當前值
public boolean contians(int key) {
Node tep = head.next;
while (tep != tail) {
if (tep.val == key)
return true;
tep = tep.next;
}
return false;
}
//移除第一個包含key的節點
public void remove(int key) {
if (contians(key)) {
Node cur = head.next;
while (cur != tail) {
if (cur.val == key) {
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
return;
} else {
cur = cur.next;
}
}
}
}
//移除所有包含key的節點
public void removeALLKey(int key) {
if (contians(key)) {
Node cur = head.next;
while (cur != tail) {
if (cur.val == key) {
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
}
cur = cur.next;
}
} else {
return;
}
}
//得到連結串列中的結點個數
public int getLength() {
int len = 0;
Node cur = head.next;
while (cur != tail) {
len++;
cur = cur.next;
}
return len;
}
//列印連結串列
public void dispaly() {
Node cur = head.next;
while (cur != tail) {
System.out.print(cur + " ");
cur = cur.next;
}
System.out.println();
}
//清空連結串列
public void clear() {
Node cur = head.next;
while (cur != tail) {
Node next = cur.next;
cur.next = null;
cur.prev = null;
}
head.next = null;
head = null;
tail.prev = null;
tail = null;
}
public static void main(String[] args) {
DoubleLinedList list = new DoubleLinedList();
list.addFirst(1);
list.addFirst(3);
list.addFirst(2);
list.addFirst(4);
list.dispaly();
list.addLast(5);
list.addLast(3);
list.addLast(15);
list.addLast(15);
list.dispaly();
System.out.println(list.contians(3));
list.remove(3);
list.dispaly();
list.removeALLKey(3);
list.dispaly();
System.out.println(list.getLength());
}
}
class Node {
int val;
Node next;
public Node() {
}
Node prev;
public Node(int val) {
this.val = val;
}
@Override
public String toString() {
return "Node{" +
"val=" + val +
'}';
}
}