JAVA容器-類比LinkedList實現(雙鏈表)

來源:互聯網
上載者:User

標籤:rem   color   提高   public   images   blog   結構   dex   查詢   

一、概述

  LinkedList實質上就是雙向鏈表的拓展的實現,我們將關注一下問題。LinkedList

  1、雙向鏈表怎麼來實現插入、刪除、查詢?

  2、利用二分法提高查詢效率。

  3、不同步,線程不安全,需要使用Collections.synchronizedList()達到安全執行緒。

  4、簡單說,LinkedList就是資料結構中關於資料操作嗎?

二、類比實現

1、實現總體圖(初始狀態)

2、論述雙鏈表的實現思想

  雙向鏈表也叫雙鏈表,是鏈表的一種,它的每個資料結點中都有兩個指標,分別指向直接後繼和直接前驅。所以,從雙向鏈表中的任意一個結點開始,都可以很方便地訪問它的前驅結點和後繼結點。查詢即從第一個節點,不斷指向下一節點以便獲得自己目標節點。刪除、插入同理,最後修改目標節點的前後關係即可,就不多論述了。

3、採用二分法,向下遍曆節點

 1  public Node node(int index){ 2         Node temp=first; 3     //採用二分法遍曆節點 4         if(index<size<<1){ 5             for(int i=0;i<index;i++){ 6                 temp=temp.getNext(); 7             } 8         }else{ 9             for(int i=size-1;i>index;i--){10                 temp=temp.getPrevious();11             }12         }13         return temp;14     }

4、查詢

1 public Object get(int index){2         checkRange(index);3         Node temp=null;4         if(null!=first){5             temp=node(index);6         }7         return temp.getObj();8  }

5、插入一個元素(頭部插入、尾部插入、中間插入)

public void add(int index,Object obj){        checkRange(index);        //移動指標,指向索引位置的節點        Node temp=node(index);        //從中間任任意一個位置插入        if(first!=null){            //建立一個新節點            Node n=new Node();            //修改當前節點的前後節點            Node before=temp.getPrevious();            n.setPrevious(before);            n.setNext(temp);            n.setObj(obj);            before.setNext(n);            temp.setPrevious(n);        }    }    public void add(Object obj){        Node n=new Node();        //如果隊頭為空白從隊頭插入        if(first==null){            //初始狀態:頭尾指標指向第一個節點            n.setObj(obj);            n.setPrevious(null);            n.setNext(null);            first=n;            last=n;        }else{            //從隊尾部插入            n.setObj(obj);            n.setPrevious(last);            n.setNext(null);            //上一個實現的next指向下一個節點            last.setNext(n);            last=n;        }        size++;    }

 6、刪除

 1 public void remove(int index){ 2     checkRange(index); 3      if (null!=first){ 4         //遍曆直到目標節點 5         Node temp=node(index); 6          Node befor=temp.getPrevious(); 7          Node after=temp.getNext(); 8          after.setPrevious(befor); 9          befor.setNext(after);10           size--;11       }12 }

7、源於揭秘LinkedList的核心部分,就沒有贅述所有實現的方法。

JAVA容器-類比LinkedList實現(雙鏈表)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.