一、概述
二、代码
public class DoubleLinkedList<E> {
public static void main(String[] args) {
System.out.println("双向链表的测试");
HashMap<String, String> map = new HashMap<>();
map.put("truename","宋江");
map.put("nickname","及时雨");
HashMap<String, String> map1 = new HashMap<>();
map1.put("truename","卢俊义");
map1.put("nickname","玉麒麟");
HashMap<String, String> map2 = new HashMap<>();
map2.put("truename","吴用");
map2.put("nickname","智多星");
HashMap<String, String> map3 = new HashMap<>();
map3.put("truename","林冲");
map3.put("nickname","豹子头");
DoubleLinkedList<HashMap> head = new DoubleLinkedList<>();
head.addLast(map);
head.addLast(map1);
head.addLast(map2);
head.addLast(map3);
head.list();
HashMap<String, String> newMap = new HashMap<>();
newMap.put("truename","宋江11111");
newMap.put("nickname","及时雨111111");
head.set(3, newMap);
System.out.println("修改后的链表情况");
head.list();
head.remove(3);
System.out.println("删除后的链表情况~~");
head.list();
}
int size = 0;
Node<E> first;
Node<E> last;
public DoubleLinkedList() {
}
public E getFirst() {
final Node<E> f = first;
return f.item;
}
public void addLast(E e) {
linkLast(e);
}
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
@Override
public String toString() {
return item.toString();
}
}
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
}
private void checkElementIndex(int index) {
if (!(index >= 0 && index < size))
throw new IndexOutOfBoundsException();
}
E unlink(Node<E> x) {
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
return element;
}
Node<E> node(int index) {
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
public void list() {
if (first.next == null) {
System.out.println("链表为空");
return;
}
Node temp = first.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
|