public class Node {
Node previous; // 前一个节点
Object element; // 本节点保存的数据
Node next; // 后一个节点
public Node(Node previous, Object element, Node next) {
super();
this.previous = previous;
this.element = element;
this.next = next;
}
public Node(Object element) {
super();
this.element = element;
}
}
public class WhLinkedList<E> {
private Node first; // 第一个节点
private Node last; // 最后一个节点
private int size;
// [] [a] [a,b]
public void add(E element) {
Node node = new Node(element);
if (first == null) { // 如果第一次放,则Node就是first
first = node;
last = node;
} else { // 如果后续放入,在结尾增加即可
node.previous = last; // 节点的上一个就是之前的最后一个
node.next = null; // 节点的下一个依然是空
// 同时之前的最后节点要指向新增加的节点
last.next = node;
last = node;
}
size++;
}
// add 插入节点
public void add(int index, E element) {
Node node = new Node(element);
Node temp = getNode(index);
if (temp != null) {
Node up = temp.previous;
up.next = node;
node.previous = up;
node.next = temp;
temp.previous = node;
} else { // 如果是空的,代表第一次添加
first = node;
last = node;
}
size++;
}
@SuppressWarnings("unchecked")
public E get(int index) {
checkRank(index);
Node temp = getNode(index);
return temp != null ? (E)temp.element : null;
}
private Node getNode(int index) {
Node temp = null;
if (index <= (size >> 1)) {
temp = first;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
} else {
temp = last;
for (int i = size - 1; i > index; i--) {
temp = temp.previous;
}
}
return temp;
}
// remove 移除节点
public void remove(int index) {
checkRank(index);
Node temp = getNode(index);
if (temp != null) {
Node up = temp.previous;
Node down = temp.next;
if (up != null) {
up.next = down;
}
if (down != null) {
down.previous = up;
}
if (index == 0) { // 如果是第一个
first = down;
}
if (index == size - 1) { // 如果是最后一个
last = up;
}
size--;
}
}
private void checkRank(int index) {
// 判断索引是否合法
if (index < 0 || index > size - 1) {
throw new RuntimeException("索引不合法:" + index);
}
}
@Override
public String toString() {
Node temp = first;
StringBuilder sb = new StringBuilder("[");
while (temp != null) {
sb.append(temp.element + " ");
temp = temp.next;
}
if (sb.length() > 1) {
sb.setCharAt(sb.length() - 1, ']');
} else {
sb.append("]");
}
return sb.toString();
}
public static void main(String[] args) {
WhLinkedList<String> list = new WhLinkedList<>();
list.add("aa");
list.add("bb");
list.add("cc");
list.add("hh");
System.out.println(list);
System.out.println(list.get(2));
// System.out.println(list.get(4));
System.out.println(list.get(3));
list.remove(2);
System.out.println(list);
list.remove(0);
System.out.println(list);
list.remove(1);
System.out.println(list);
list.remove(0);
System.out.println(list);
list.add(0, "AA");
System.out.println(list);
}
}