实现类
package day03;
public class DoubleLinkedList {
private Node headNode;
private Node lastNode;
private int size;
public int size(){
return this.size;
}
public void add(Object element){
Node node = new Node(element);
if (headNode == null){
headNode = node;
lastNode = node;
}else {
lastNode.next = node;
node.pre = lastNode;
lastNode = node;
}
size ++;
}
public Object get(int index){
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("序号不合法,index:" + index);
Node node = node(index);
return node.data;
}
public void remove(int index){
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("序号不合法,index:" + index);
if (index == 0){
Node nextNode = headNode.next;
headNode.next = null;
if (nextNode != null)
nextNode.pre = null;
headNode = nextNode;
}
else if (index == size - 1){
Node preNode = lastNode.pre;
preNode.next = null;
lastNode.pre = null;
lastNode = preNode;
}
else {
Node delNode = node(index);
Node preNode = delNode.pre;
Node nextNode = delNode.next;
preNode.next = nextNode;
nextNode.pre = preNode;
delNode.pre = null;
delNode.next = null;
}
size --;
}
public void add(int index,Object element){
if (index < 0 || index > index)
throw new IndexOutOfBoundsException("序号不合法,index:" + index);
Node node = new Node(element);
if (index == 0){
node.next = headNode;
headNode.pre = node;
headNode = node;
}
else if (index == size){
add(element);
}
else {
Node curNode = node(index);
Node preNode = curNode.pre;
preNode.next = node;
node.pre = preNode;
node.next = curNode;
curNode.pre = node;
}
size ++;
}
private Node node(int index){
if (index < size / 2){
Node nextNode = headNode;
for (int i = 0; i < index; i++) {
nextNode = nextNode.next;
}
return nextNode;
}
else {
Node preNode = lastNode;
for (int i = size - 1; i > index; i--) {
preNode = preNode.pre;
}
return preNode;
}
}
private static class Node{
private Object data;
private Node pre;
private Node next;
public Node(Object data) {
this.data = data;
}
}
}
测试类
package day03;
public class Test03 {
public static void main(String[] args) {
DoubleLinkedList list = new DoubleLinkedList();
list.add("11");
list.add("22");
list.add("33");
list.add(3,"1");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
|