双向链表,java代码
时间: 2024-06-05 08:04:01 浏览: 21
双向链表是一种常见的数据结构,它可以在每个节点中保存指向前一个节点和后一个节点的指针,因此可以实现双向遍历。
以下是 Java 实现双向链表的示例代码:
```
public class DoublyLinkedList {
private Node head;
private Node tail;
private class Node {
int value;
Node prev;
Node next;
Node(int value) {
this.value = value;
this.prev = null;
this.next = null;
}
}
public DoublyLinkedList() {
this.head = null;
this.tail = null;
}
public void addFirst(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}
public void addLast(int value) {
Node newNode = new Node(value);
if (tail == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
public void removeFirst() {
if (head == null) {
throw new NoSuchElementException();
}
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
head.prev = null;
}
}
public void removeLast() {
if (tail == null) {
throw new NoSuchElementException();
}
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.prev;
tail.next = null;
}
}
public int getFirst() {
if (head == null) {
throw new NoSuchElementException();
}
return head.value;
}
public int getLast() {
if (tail == null) {
throw new NoSuchElementException();
}
return tail.value;
}
}
```