双向带环链表—头插
DLinkedList.java
class DLinkedNode {
int val = 0;
DLinkedNode prev = null;
DLinkedNode next = null;
DLinkedNode(int val) {
this.val = val;
}
}
public class DLinkedList {
DLinkedNode head = null;
public DLinkedList() {
head = new DLinkedNode(-1);
head.next = head;
head.prev = head;
}
public void addFirst(int data) {
DLinkedNode newNode = new DLinkedNode(data);
DLinkedNode next = head.next;
head.next = newNode;
newNode.next = next;
newNode.prev = head;
next.prev = newNode;
}
public void display() {
System.out.print("正向:[");
for (DLinkedNode cur = head.next;
cur != head;
cur = cur.next) {
System.out.print(cur.val);
if (cur.next != head) {
System.out.print(", ");
}
}
System.out.println("]");
System.out.print("反向: [");
for (DLinkedNode cur = head.prev;
cur != head; cur = cur.prev) {
System.out.print(cur.val);
if (cur.prev != head) {
System.out.print(",");
}
}
System.out.println("]");
}
}
TestDLinkedList.java
public class TestDLinkedList {
public static void main(String[] args) {
testAddFirst();
}
public static void testAddFirst() {
System.out.println("测试双向链表中的头插");
DLinkedList dLinkedList = new DLinkedList();
dLinkedList.addFirst(1);
dLinkedList.addFirst(2);
dLinkedList.addFirst(3);
dLinkedList.addFirst(4);
dLinkedList.display();
}
}