1. 程式人生 > >Java 連結串列的底層實現

Java 連結串列的底層實現

package com.soto.collection;


/**
 * add 和 get方法
 * 
 * @author 王
 *
 */
public class SxtLinkedList /*implements List*/ {  //雙向連結串列,
	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 {
			//直接在last結點後增加新的結點
			n.setPrevious(last);
			n.setObj(obj);
			n.setNext(null);
			
			last.setNext(n);
			last = n;
		}	
		size++;
	}
	public int size(){
		return size;
	}
	public Object get(int index){   
		rangeCheck(index);
		Node temp = node(index);
		if(temp!=null){
			return temp.obj;
		}
		return null;
	}
	
	private void rangeCheck(int index){
		if(index<0||index>size){
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
	}
	public Node node(int index){
		Node temp = null;
		if(first != null){
			temp = first;		
			for(int i=0;i<index;i++){
				temp = temp.next;
			}	
		}
		return temp;
	}
	
	
	public void remove(int index){
		Node temp = null;
		if (first != null) {
			temp = first;
			for(int i =0 ; i<index;i++){
				temp = temp.next;
			}
			if (temp!=null) {
				Node up = temp.previous;
				Node down = temp.next;
				up.next = down;
				down.previous = up;
				size--;
			}
		}
		
	}
	
	public void add(int index, Object obj){
		Node temp = node(index);
		Node newNode = new Node();
		newNode.obj = obj;
		
		if(temp !=null){
			Node up = temp.previous;
			up.next = newNode;    //雙向 !!
			newNode.previous = up;
			
			
			newNode.next = temp;  //雙向!!
			temp.previous = newNode;
			size++;
		}
		
	}
	public static void main(String[] args) {
		SxtLinkedList list = new SxtLinkedList();
		list.add("aaa");
		list.add(1, "BBB");
		list.add("bbb");
		list.add("ccc");
	//	list.remove(1);
		System.out.println(list.get(1));
	}
	
	

}