java 用双向链表实现SJBLinkedList

 

public class SJBLinkedList{

 

private Node first;

 

private Node last;

 

private int size;

 

public int size(){

return size;

}

 

public boolean isEmpty(){

return size == 0;

}

 

public void add(Object obj){

 

Node node = new Node();

 

if(first == null){

 

node.obj = obj;

node.previous = null;

node.next = null;

 

first = node;

last = node;

 

}else{

 

node.obj = obj;

node.previous = last;

node.next = null;

 

last.next = node;

last = node;

 

}

 

size++;

 

}

 

 

private Node getNode(int index){

 

if(index < 0 || index >size ){

try {

throw new Exception();

} catch (Exception e) {

 

e.printStackTrace();

System.exit(0);

}

}

 

Node temp = null;

 

if(first != null){

temp = first;

for (int i=0;i<index;i++){

temp = temp.next;

}

}

 

return temp; 

 

}

 

 

public Object get(int index){

return getNode(index).obj;

}

 

public void remove(int index){

 

if(index < 0 || index >size ){

try {

throw new Exception();

} catch (Exception e) {

 

e.printStackTrace();

System.exit(0);

}

}

 

Node currentNode = getNode(index);

Node upNode = currentNode.previous;

Node downNode = currentNode.next;

 

upNode.next = downNode;

downNode.previous = upNode;

 

size--;

 

}

 

 

private class Node{

 

private Node previous;

 

private Object obj;

 

private Node next;

 

public Node(Node previous,Node next,Object obj){

this.previous = previous;

this.obj = obj;

this.next = next;

}

 

public Node(){

 

}

 

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;

}

 

 

}

 

 

 

public static void main(String[] args){

 

SJBLinkedList list = new SJBLinkedList();

list.add("123");

list.add("234");

list.add("345");

 

for(int i=0;i<3;i++){

System.out.println(list.get(i));

}

 

//System.out.println(list.get(5));

 

}

 

 

}

posted @ 2016-09-14 09:36  sujianbo  阅读(151)  评论(0编辑  收藏  举报