模擬LinkedList底層實現的示例
阿新 • • 發佈:2018-12-21
這個示例的目的是模擬連結串列的實現方式,與ArrayList的底層實現相比查詢慢,增刪改快的優缺點。
package test; public class DesignLinkedList { private int size; private Node first; private Node last; public void add(Object obj) { Node n = new Node(); if(first==null) { n.setPrevious(null); n.setSelfObj(obj); n.setNext(null); first =n; last =n; }else { //直接往最後一個節點處新增 n.setPrevious(last); n.setSelfObj(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); return temp.getSelfObj(); } public Node Node(int index) { rangeCheck(index); Node temp =null; if(first !=null) { temp = first; for(int i=0; i<index;i++) { temp=temp.getNext(); } } return temp; } private void rangeCheck(int index) { if (index < 0 || index >= size) { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } } public void remove(int index) { rangeCheck(index); Node temp=Node(index); if(temp!=null) { Node up=temp.getPrevious(); Node down = temp.getNext(); if(down !=null) { down.setPrevious(up); } up.setNext(down); size--; } } public void add(int index, Object obj) { rangeCheck(index); //先獲取當前位置的節點 Node currentNode = Node(index); //建立新節點 Node temp = new Node(); temp.setSelfObj(obj); if(currentNode!=null){ Node up= currentNode.getPrevious(); up.setNext(temp); temp.setNext(currentNode); size++; } } public static void main(String[] arg) throws Exception { DesignLinkedList dll= new DesignLinkedList(); //當只有"aaa"一個元素被新增的話,first 和 last的都是aaa, 節點的previous 和next的物件都是null dll.add("aaa"); //第二個元素被新增之後,將當前last節點的next物件設定為ccc,然後然後將當前物件設定為last物件。 dll.add("cccc"); dll.add("bbb"); System.out.println(dll.size()); System.out.println(dll.get(0)); System.out.println(dll.get(1)); dll.remove(2); System.out.println(dll.size); dll.add(1,"eee"); System.out.println(dll.size); System.out.println(dll.get(1)); } }
package test; //用來定義連結串列中的一個節點 public class Node { private Node previous; private Object selfObj; private Node next; public Node() { super(); } public Node(Node previous, Object selfObj, Node next) { super(); this.previous = previous; this.selfObj = selfObj; this.next = next; } public Node getPrevious() { return previous; } public void setPrevious(Node previous) { this.previous = previous; } public Object getSelfObj() { return selfObj; } public void setSelfObj(Object selfObj) { this.selfObj = selfObj; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } }