public class Node {
Node previous;
Object obj;
Node next;
public Node(){
}
public Node(Node previous, Object obj, Node next) {
this.previous = previous;
this.obj = obj;
this.next =next;
}
}
public class MyArraylistBylink {
Node first; //首结点
Node last; //尾结点
int size;
public MyArraylistBylink(){
}
public int size(){
return size;
}
public void add(Object obj){
Node temp=new Node();
temp.obj=obj;
if(first==null){ //如果为空的话,首尾都是他
first=temp;
last=temp;
}else{
last.next=temp; //不为空,把尾连上他,再把尾设置为他就好了
temp.previous=last;
last=temp;
}
size++;
}
public void add(Object obj,int index){
Node temp=node(index);
Node up=temp.previous;
Node newnode=new Node();
up.next=newnode;
newnode.obj=obj;
newnode.next=temp;
temp.previous=newnode;
}
private Node node(int index){
checkRang(index);
Node temp=first; //不能直接对首结点操作,会丢失这个链表的
for(int i=0;i<index;i++){ //需要遍历才能找到索引位置的内容
temp=temp.next;
}
return temp;
}
public Object get(int index){
Node temp=node(index);
return temp.obj;
}
public Object remove(int index){
Node temp=node(index);
Object oldValue=temp.obj;
Node up=temp.previous;
Node down=temp.next;
up.next=down;
down.previous=up;
temp=null;
return oldValue;
}
public void checkRang(int index){
if(index>=size||index<0){
try {
throw new Exception("Out of Bounds!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyArraylistBylink list=new MyArraylistBylink();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6", 2);
System.out.println(list.get(3));
}
}
网友评论