1. 概述
- 雙向鏈表:每一個節點存在前項指針和後項指針,方便對於節點的操做。不須要,考慮如何獲取前項節點而苦惱。
2. 源碼
public class TwoWayList<T> {
public class Node {
public T data;
private Node next, prev;
public Node(T e, Node next) {
this.data = e;
this.next = next;
}
public Node(T e) {
this(e, null);
}
public Node() {
this(null, null);
}
@Override
public String toString() {
return data.toString();
}
}
private Node head, tail;
private int size;
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void add(T e) {
if (tail == null) {
tail = new Node(e);
head = tail;
} else {
Node newNode = new Node(e);
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
size++;
}
public void addFirst(T e) {
if (tail == null) {
tail = new Node(e);
head = tail;
} else {
Node newNode = new Node(e);
head.prev = newNode;
newNode.next = head;
head = newNode;
}
size++;
}
public void addLast(T e) {
add(e);
}
public T removeFirst() {
if (tail == null) {
throw new IllegalArgumentException("List is empty!");
}
Node cur = head;
head = head.next;
cur.next = null;
size--;
return cur.data;
}
public T removeLast() {
if (tail == null) {
throw new IllegalArgumentException("List is empty!");
}
Node cur = tail;
tail = tail.prev;
tail.next = null;
cur.prev = null;
size--;
return cur.data;
}
public T getFirst() {
if (tail == null) {
throw new IllegalArgumentException("List is empty!");
}
return head.data;
}
public T getLast() {
if (tail == null) {
throw new IllegalArgumentException("List is empty!");
}
return tail.data;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
Node cur = head;
while (cur != null) {
result.append(cur + "->");
cur = cur.next;
}
result.append("Null");
return result.toString();
}
public static void main(String[] args) {
TwoWayList<Integer> list = new TwoWayList<>();
IntStream.range(0, 10).forEach(item -> {
list.addFirst(item);
System.out.println(list);
});
System.out.println("==========DEL First==========");
IntStream.range(0, 3).forEach(item -> {
list.removeFirst();
System.out.println(list);
});
System.out.println("==========DEL Last==========");
IntStream.range(0, 3).forEach(item -> {
list.removeLast();
System.out.println(list);
});
System.out.println("==========GET First&Last==========");
System.out.println(list.getFirst());
System.out.println(list.getLast());
}
}