1. 程式人生 > >LinkedList底層源碼實現

LinkedList底層源碼實現

emp add 時間 新增 復雜 next 比較 try ()

/**
 * Created by chengbx on 2018/5/18.
 * LinkedList其實也就是我們在數據結構中的鏈表,這種數據結構有這樣的特性:
 * 分配內存空間不是必須是連續的;
 * 插入、刪除操作很快,只要修改前後指針就OK了,時間復雜度為O(1);
 * 訪問比較慢,必須得從第一個元素開始遍歷,時間復雜度為O(n);
 */
public class CbxLinkedList {
    private Node first;
    private Node last;
    private int size;

    public void add(Object object){
        
//如果是第一個節點 那麽在創建之後 第一個節點 也是最後一個節點 Node n = new Node(); if(first == null){ n.setPrevious(null); n.setObject(object); n.setNext(null); first = n; last = n; }else{ //直接往last後面添加新的節點 n.setPrevious(last); n.setObject(object); n.setNext(
null); //新增的節點為最後一個節點 last.setNext(n); last = n; } size++; } public Object get(int index){ RangeCheck(index); Node temp = getNodeByindex(index); return temp.getObject(); } public int size(){ return size; }
private void RangeCheck(int index){ if(index >= size){ try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } } public Node getNodeByindex(int index){ Node temp = null; if(first!=null){ temp = first; for(int i =0;i<index;i++){ temp = temp.getNext(); } } return temp; } public void remove(int index){ Node temp = getNodeByindex(index); Node preNode = temp.getPrevious(); Node nextNode = temp.getNext(); preNode.setNext(nextNode); nextNode.setPrevious(preNode); size--; } public void add(int index,Object object){ //獲取對應索引的節點 Node temp = getNodeByindex(index); if(temp!=null){ Node preNode = temp.getPrevious(); Node newNode = new Node(); newNode.setPrevious(preNode); newNode.setObject(object); newNode.setNext(temp); preNode.setNext(newNode); temp.setPrevious(newNode); } size++; } @Test public void test(){ CbxLinkedList cbxLinkedList = new CbxLinkedList(); cbxLinkedList.add("aaa"); } } class Node{ private Node previous; private Object object; private Node next; public Node getPrevious() { return previous; } public void setPrevious(Node previous) { this.previous = previous; } public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public Node() { } public Node(Node previous, Object object, Node next) { this.previous = previous; this.object = object; this.next = next; } }

LinkedList底層源碼實現