1. 程式人生 > >java LinkedList簡單實現

java LinkedList簡單實現

時間:2018/7/27

簡單是實現了LinkedList的幾個方法,還是JAVA好啊 ,沒有指標

就是對連結串列的一些簡單操作

package c11;

public class CopyLinkedList {
    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 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 Object get(int index){
    	
    	//這裡還有一個越界的判斷
    	Node temp = node(index);
    	return temp.obj;
    }
    
    public void remove(int index){
    	Node temp = node(index);
    	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) {
		CopyLinkedList list = new CopyLinkedList();
		list.add("aaa");
		list.add("bbb");
		list.add(1, "ccc");
		System.out.println(list.size());
		System.out.println(list.get(1));
		//list.remove(1);
		System.out.println(list.size());
	}
}

//表示一個節點 
class Node{
	Node previous;
	Object obj;
	Node 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;
	}
	
	
}