class DLinkedNode {
public int val = 0;
public DLinkedNode prev = null;
public DLinkedNode next = null;
public DLinkedNode(int val) {
this.val = val;
}
}
public class DLinkedList {
private 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;
newNode.next = next;
head.next = newNode;
next.prev =newNode;
newNode.prev = head;
}
//打印双向链表
public void disPlay() {
System.out.print("正向: [");
DLinkedNode cur = head.next;
while (cur != head) {
if (cur.next == head) {
System.out.println(cur.val+"]");
cur = cur.next;
} else {
System.out.print(cur.val + ", ");
cur = cur.next;
}
}
System.out.print("反向: [");
DLinkedNode temp = head.prev;
while (temp != head) {
if (temp.prev == head) {
System.out.println(temp.val+"]");
temp = temp.prev;
} else {
System.out.print(temp.val+", ");
temp = temp.prev;
}
}
}
//尾插
public void addLast(int data) {
DLinkedNode newNode = new DLinkedNode(data);
DLinkedNode prev = head.prev;
head.prev = newNode;
newNode.prev = prev;
prev.next = newNode;
newNode.next =head;
}
//插入下标为index的任意位置
public void addIndex(int index, int data) {
int size = size();
if (index < 0 || index > size) {
return;
}
if (index == 0) {
addFirst(data);
}
if (index == size) {
addLast(data);
}
DLinkedNode next = getPos(index);
DLinkedNode prev = next.prev;
DLinkedNode newNode = new DLinkedNode(data);
next.prev = newNode;
newNode.prev = prev;
prev.next = newNode;
newNode.next = next;
}
//找到index下标对应的结点
public DLinkedNode getPos(int index) {
DLinkedNode cur = head.next;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
return cur;
}
//获取链表长度
public int size() {
int size = 0;
for (DLinkedNode cur = head.next;
cur != head; cur = cur.next) {
size += 1;
}
return size;
}
//判断某个元素是否存在
public boolean contains(int toFind) {
for (DLinkedNode cur = head.next; cur!= head; cur = cur.next) {
if (cur.val == toFind) {
return true;
}
}
return false;
}
//删除第一次出现key的结点
public void remove(int key) {
DLinkedNode next = head.next.next;
DLinkedNode prev = head;
for (DLinkedNode cur = head.next;
cur != null; cur = cur.next) {
prev = prev.next;
next = next.next;
if (cur.next.val == key) {
prev.next = next;
next.prev = prev;
return;
}
}
return;
}
//删除所有key的结点
public void removeAll(int key) {
while (true) {
DLinkedNode next = head.next.next;
DLinkedNode prev = head;
for (DLinkedNode cur = head.next;
cur != null; cur = cur.next) {
prev = prev.next;
next = next.next;
if (cur.next.val == key) {
prev.next = next;
next.prev = prev;
}
}
return;
}
}
//得到一个初始状态下的空链表
//对于我们当前这样的链表来说,
//初始状态带有一个傀儡结点。
public void clean() {
head.next = head;
head.prev = head;
}
}