雙向連結串列的操作
//基於雙向連結串列演算法的集合 //建立一個內部類儲存節點 private Node first;//第一個節點物件 private Node last;//最後一個節點物件 private int size;//連結串列的節點物件的個數 public void remove(Object ele) { //找到被刪除的節點 Node current = this.first;//第一個節點 //遍歷節點 for (int i = 0; i < size; i++) { if(!current.ele.equals(ele)) { if(current.next==null) { return; } current = current.next; } } // System.out.println(current.ele); //刪除節點 if(current==first) { this.first = current.next; this.first.prev = null; }else if(current==last) { this.last = current.prev; this.last.next = null; }else { current.prev.next = current.next; current.next.prev = current.prev; } size--;//這個千萬別忘了 } public void addLast(Object ele) { Node node = new Node(ele);//需要儲存的節點物件 if(size==0) {//這個節點物件既是第一個也是最後一個 this.first = node; this.last = node; }else { this.last.next = node; node.prev = this.last; this.last = node; } size++; } public void addFirst(Object ele) { Node node = new Node(ele);//需要儲存的節點物件 if(size==0) {//這個節點物件既是第一個也是最後一個 this.first = node; this.last = node; }else { node.next = this.first; this.first.prev = node; this.first = node; } size++; } public String toString() { if(size==0) { return "[]"; } Node current = this.first;//第一個節點 StringBuilder str = new StringBuilder(size*2+1); str.append("["); for (int i = 0; i < size; i++) { str.append(current.ele); if(i!=size-1) { str.append(","); }else { str.append("]"); } current = current.next; } return str.toString(); } /* * 連結串列中的節點 */ class Node{ Node prev;//上一個節點物件 Node next;//下一個節點物件 Object ele;//當前節點的元素 public Node(Object ele) { this.ele = ele;//將元素賦值給該節點 } }