public class MyLinkedList{
private Node first;
private Node last;
private int size;
public void add(Object obj) {
Node n = new Node();
if (first == null) {
n.setPrevious(null);
n.setObj(obj);
n.setNext(null);
first = n;
last = n;
} else {
n.setPrevious(last);
n.setObj(obj);
n.setNext(null);
last.setNext(n);
last = n;
}
size++;
}
public void add(int index, Object obj) {
Node temp = node(index);
Node newNode = new Node();
newNode.setObj(obj);
if (temp != null) {
Node up = temp.getPrevious();
up.setNext(newNode);
newNode.setPrevious(up);
newNode.setNext(temp);
temp.setPrevious(newNode);
size++;
}
}
public int size() {
return size;
}
private void rangeCheck(int index) {
if (index < 0 || index >= size) {
try {
throw new IndexOutOfBoundsException("数组下标越界");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Object get(int index) {
rangeCheck(index);
Node temp = node(index);
if (temp != null) {
return temp.getObj();
}
return null;
}
public Node node(int index) {
Node temp = null;
if (first != null) {
if (index < (size >> 1)) {
temp = first;
for (int i = 0; i < index; i++) {
temp = temp.getNext();
}
} else {
temp = last;
for (int i = size - 1; i > index; i--) {
temp = temp.getPrevious();
}
}
}
return temp;
}
public void remove(int index) {
Node temp = node(index);
if (temp != null) {
Node up = temp.getPrevious();
Node down = temp.getNext();
up.setNext(down);
down.setPrevious(up);
size--;
}
}
public Object set(int index, Node element) {
rangeCheck(index);
Node x = node(index);
Object oldVal = x.getObj();
x.setObj(element);
return oldVal;
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
list.add("eee");
System.out.println(list.get(3));
}
}
public class Node {
private Node previous;
private Object obj;
private Node next;
public Node() {
}
public Node(Node previous, Object obj, Node next) {
this.previous = previous;
this.obj = obj;
this.next = next;
}
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}