java实现双向链表

时间:2024-01-10 22:48:26
PS:双向链表(每个节点含有指向前一个节点的前驱与后一个节点的后继)

public class DoublyLinkedList {
static class Node {
private Object data;
private Node prev; public Node getPrev() {
return prev;
} public void setPrev(Node prev) {
this.prev = prev;
} private Node next; public Node(Object value) {
this.data = value;
} public Object getData() {
return data;
} public void setData(Object data) {
this.data = data;
} public Node getNext() {
return next;
} public void setNext(Node next) {
this.next = next;
} @Override
public String toString() {
return String.valueOf(data);
}
} private Node head;// 头节点 public DoublyLinkedList() {
head = new Node(null);
} // 双向链表表头插入节点
public void addFirst(Object value) {
Node node = new Node(value);
if (head.next == null) {
head.next = node;
node.prev = head;
} else {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
// head=node;
} // 删除表头
public void removeFirst() {
Node node = head.next;
if (node.next != null) {
node.next.prev = head;
head.next = node.next;
}
} // 顺序打印链表
public void printList() {
Node node = head.next;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
} // 逆序打印链表
public void reversePrintList() {
Node node = head.next;
Node tail = null;
while (node.next != null) {
node = node.next;
}
tail = node;
// System.out.println(tail.data);
while (tail.prev != null) {
System.out.print(tail.data + " ");
tail = tail.prev;
}
System.out.println();
} public static void main(String[] args) {
DoublyLinkedList linkedList = new DoublyLinkedList();
for (int i = 0; i < 10; i++) {
linkedList.addFirst(i);
}
System.out.println("顺序打印链表");
linkedList.printList();
System.out.println("逆序打印链表");
linkedList.reversePrintList();
System.out.println("依次删除头结点");
for (int i = 0; i < 10; i++) {
linkedList.removeFirst();
linkedList.printList();
} }
}