1. 程式人生 > >Java數據結構——雙向鏈表

Java數據結構——雙向鏈表

.com bubuko http 分享圖片 null wid string 元素 java數據結構

什麽是雙向鏈表?
每一個結點不僅配有next引用,同時還有一個prev引用,指向其上一個結點(前驅結點), 沒有前驅的時候就為NULL。

技術分享圖片

(以下圖片均來自網絡,侵刪)

與單鏈表的區別?
和單向鏈表相比有以下優勢:

  1. 插入刪除不需要移動元素外,可以原地插入刪除
  2. 可以雙向遍歷

插入操作

技術分享圖片

刪除操作

技術分享圖片

實現

public class DLNode {
Object data;
DLNode prev;
DLNode next;
static DLNode head;
static DLNode tail;

// 無參構造
public DLNode() {
super();
}

// 有參構造
public DLNode(Object data, DLNode prev, DLNode next) {
super();
this.data = data;
this.prev = prev;
this.next = next;
}

// 獲取數據
public Object getData() {
return data;
}

// 修改數據
public void setData(Object data) {
this.data = data;
}

// 得到前驅結點
public DLNode getPrev() {
return prev;
}

// 修改前驅結點
public void setPrev(DLNode prev) {
this.prev = prev;
}

// 獲取後驅結點
public DLNode getNext() {
return next;
}

// 修改後驅結點
public void setNext(DLNode next) {
this.next = next;
}

// 獲取長度
public static int getLength() {
int count = 0;
for (DLNode n = head; n != null; n = n.next) {
count++;
}
return count;
}

// 插入結點
public static void add(Object data, int index) {
DLNode node = new DLNode(data, null, null);
if (index == 0) {
node.next = head;
node.prev = null;
head = node;
} else if (index == getLength()) {
tail.next = node;
node.prev = tail;
tail = node;

} else {
int temp = 0;
for (DLNode n = head; n != null; n = n.next) {
temp++;
if (temp == index) {
node.next = n.next;
n.next.prev = node;
n.next = node;
node.prev = n;
break;
}
}
}
}

//刪除結點
public static void remove(int index) {
if (index == 0) {
head = head.next;
head.prev = null;
} else if (index == getLength() - 1) {
tail = tail.prev;
tail.next = null;
} else if (index >= getLength()) {
System.out.println("超出鏈表長度");
System.exit(0);
} else {
int temp = 0;
for (DLNode n = head; n != null; n = n.next) {
temp++;
if (temp == index) {
n.next = n.next.next;
n.next.prev = n;
break;
}
}
}
}

public static void main(String[] args) {
DLNode node1 = new DLNode("aaa", null, null);
DLNode node2 = new DLNode("bbb", node1, null);
DLNode node3 = new DLNode("ccc", node2, null);
DLNode node4 = new DLNode("ddd", node3, null);
node3.setNext(node4);
node2.setNext(node3);
node1.setNext(node2);
head = node1;
tail = node4;
System.out.print("當前鏈表:");
for (DLNode n = head; n != null; n = n.next) {
System.out.print(n.data + " ");
}
System.out.println();
System.out.println("鏈表長度:" + getLength());
add("eee", 4);
System.out.print("插入後鏈表:");
for (DLNode n = head; n != null; n = n.next) {
System.out.print(n.data + " ");
}
System.out.println();
remove(0);
System.out.print("刪除後鏈表:");
for (DLNode n = head; n != null; n = n.next) {
System.out.print(n.data + " ");
}
}
}

  

Java數據結構——雙向鏈表