public class Node {
Node prev;
Object obj;
Node next;
public Node() {
}
public Node(Node prev, Object obj, Node next) {
this.prev = prev;
this.obj = obj;
this.next = next;
}
public Node getPrev() {
return prev;
}
public Object getObj() {
return obj;
}
public Node getNext() {
return next;
}
public void setPrev(Node prev) {
this.prev = prev;
}
public void setObj(Object obj) {
this.obj = obj;
}
public void setNext(Node next) {
this.next = next;
}
public class MyLinkedList {
//第一个节点
private Node first;
//最后一个节点
private Node last;
private int size;
public int size(){
return size;
}
public void add(Object obj){
Node n=new Node();
if(first==null){
n.setPrev(null);
n.setObj(obj);
n.setNext(null);
first=n;
last=n;
}else{
n.setPrev(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.obj=obj;
if(temp!=null){
Node preNode=temp.prev;
preNode.next=newNode;
newNode.prev=preNode;
temp.prev=newNode;
newNode.next=temp;
size++;
}
}
//在使用get方法的时候把Node的私有属性去掉,方便理解
public Object get(int index){
rangeCheck(index);
Node temp=node(index);
if(temp!=null){
return temp.obj;
}else {
return null;
}
}
public void set(int index,Object obj){
rangeCheck(index);
Node temp=node(index);
temp.obj=obj;
}
public void remove(int index){
rangeCheck(index);
Node temp=node(index);
if(temp!=null){
Node preNode=temp.prev;
Node nexNode=temp.next;
preNode.next=nexNode;
nexNode.prev=preNode;
size--;
}
}
//获得index处的节点
private Node node(int index){
Node temp=null;
if(first!=null){
temp=first;
for(int i=0;i<index;i++){
temp=temp.next;
}
}
return temp;
}
//检查索引
private void rangeCheck(int index){
if(index<0||index>=size){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyLinkedList list=new MyLinkedList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add(1,"BBB");
list.set(3,"CCC");
System.out.println(list.get(1));
}
}