public class LinkedList2<E> { //另外一種思路 // 內存空間不是連續的 即物理空間不是連續的 邏輯空間依賴着next指向是連續的 private class Node{ public E e; public Node next; public Node(E e, Node next){ this.e = e; this.next = next; } public Node(E e){ this(e,null); } public Node(){ this(null,null); } @Override public String toString(){ return e.toString(); } } private Node dummyHead; //虛擬頭結點,在頭結點前面創建一個節點 private int size; public LinkedList2(){ dummyHead = new Node(); size = 0; } //獲取鏈表中元素個數 public int getSize(){ return size; } public boolean isEmpty(){ return size == 0; } public void addFirst(E e){ add(0,e); } //在指定位置添加結點 // 由於並不常見 所以我們定義head 為 第 0 個元素 public void add(int index, E e){ if (index < 0 || index > size){ throw new IllegalArgumentException("指定位置越界"); } if(index == 0){ addFirst(e); }else{ Node pre = dummyHead; for (int i = 0 ; i < index ; i++){ pre = pre.next; } /*Node c = new Node(e); c.next = pre.next; pre.next = c;*/ pre.next = new Node(e,pre.next); size--; } } public void addLast(E e){ add(size,e); } public E get(int index ){ if (index < 0 || index > size){ throw new IllegalArgumentException("越界"); } Node cur = dummyHead.next; for (int i = 0 ; i < index ; i++) { cur = cur.next; } return cur.e; } public E getFirst(){ return get(0); } public E getLast(){ return get(size); } // 查詢是否存在元素e public boolean contains(E e) { Node cur = dummyHead.next; for (int i = 0; i < size; i++) { if (cur.e == e) { return true; } cur = cur.next; } return false; } public E remove(int index){ if (index < 0 || index > size){ throw new IllegalArgumentException("下標越界"); } Node cur = dummyHead; for (int i =0 ; i < index ; i++){ cur = cur.next; } Node t = new Node(); cur.next = t; cur.next = t.next; t.next = null; size --; return t.e; } public E removeFirst(){ return remove(0); } public E removeLast(){ return remove(size); } }
在head 結點的前面的創建虛擬頭結點。 為了使修改刪除 ,讓head結點和普通結點一視同仁