1.链表结构
链表是链式的结构
2.链表的组成
链表是由头节点,中间节点和尾节点组成
节点是由两个部分组成:
1.数据域
2.引用域
3.链表的实现
Node{
数据域
引用域
}
MyLinkedList{
记录元素总数的属性
头节点属性
head;
尾节点属性
trail;
}
下面上代码
public class DoubleLinkedList{
private static class Node {
Object value;
Node prev = this;
Node next = this;
Node(Object v) {
value = v;
}
public String toString() {
return value.toString();
}
}
private Node head = new Node(null);
// 头节点
private int size;
// 链表大小
// 以下是接口方法
public boolean addFirst(Object o) {
addAfter(new Node(o), head);
return true;
}
public boolean addLast(Object o) {
addBefore(new Node(o), head);
return true;
}
public boolean add(Object o) {
return addLast(o);
}
public boolean add(int index, Object o) {
addBefore(new Node(o), getNode(index));
return true;
}
public boolean revise(int index, Object o) {
reviseNode(new Node(o), getNode(index));
return true;
}
public boolean remove(int index) {
removeNode(getNode(index));
return true;
}
public boolean removeFirst() {
removeNode(head.next);
return true;
}
public boolean removeLast() {
removeNode(head.prev);
return true;
}
public Object get(int index) {
return getNode(index).value;
}
public int size() {
return size;
}
public String toString() {
StringBuffer s = new StringBuffer();
Node node = head;
for (int i = 0; i < size; i++) {
node = node.next;
if (i > 0)
s.append(" ");
s.append(node.value);
}
return s.toString();
}
private Node getNode(int index) {
if (index < 0 || index >= size)
System.out.println("错误");
Node node = head.next;
for (int i = 0; i < index; i++)
node = node.next;
return node;
}
private void addBefore(Node newNode, Node node) {
newNode.next = node;
newNode.prev = node.prev;
newNode.next.prev = newNode;
newNode.prev.next = newNode;
size++;
}
private void reviseNode(Node newNode, Node node) {
newNode.next = node.next;
newNode.prev = node.prev;
newNode.next.prev = newNode;
newNode.prev.next = newNode;
}
private void addAfter(Node newNode, Node node) {
newNode.prev = node;
newNode.next = node.next;
newNode.next.prev = newNode;
newNode.prev.next = newNode;
size++;
}
private void removeNode(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
node.prev = null;
node.next = null;
size--;
}
}