1. 程式人生 > >雙向鏈表--Java實現

雙向鏈表--Java實現

pty color 多個 sem 進行 rtl double public oid

  1 /*雙向鏈表特點:
  2  *1.每個節點含有兩個引用,previos和next,支持向前或向後的遍歷(除頭節點)
  3  *2.缺點插入或刪除的時候涉及到引用修改的比較多
  4  *註意:下面的雙向鏈表其實也實現了雙端鏈表
  5  *註意:在Java中多個引用可以指向同一個對象,也可以隨時改變引用的指向
  6  *      關於修改引用細心一點就可以 引用A = 引用B 表示A引用指向B引用指向的對象
  7  *應用:利用雙向鏈表可以實現雙端隊列
  8  * */
  9 
 10 public class MyDoubleLink {
 11     private Link first;
12 private Link last; 13 14 public boolean isEmpty(){ 15 return first == null; 16 } 17 18 public void insertFirst(int key){ 19 Link newLink = new Link(key); 20 if(first == null){ 21 last = newLink; 22 } 23 else{
24 first.previous = newLink; 25 } 26 newLink.next = first;//鏈未斷可以指向同一個 27 first = newLink; 28 } 29 30 public void insertLast(int key){ 31 Link newLink = new Link(key); 32 if(first == null){ 33 first = newLink; 34 }
35 else{ 36 last.next = newLink; 37 newLink.previous = last; 38 } 39 last = newLink; 40 } 41 42 //插入指定值的後邊---其實是一種尾巴插入--此時鏈表非空才可以操作 43 public boolean insertAfter(int key,int value){ 44 Link newLink = new Link(value); 45 Link current = first; 46 while(current.id != key){ 47 current = current.next; 48 if(current == null){ 49 return false; 50 } 51 } 52 if(current == last){//find it at last item 53 newLink.next = null; 54 last = newLink; 55 } 56 else{ 57 newLink.next = current.next; 58 current.next.previous = newLink; 59 } 60 newLink.previous = current; 61 current.next = newLink; 62 return true; 63 } 64 65 public Link deleteFirst(){ 66 Link temp = first; 67 if(first.next == null){ 68 last = null; 69 } 70 else{ 71 first.next.previous = null; 72 } 73 first = first.next; 74 return temp; 75 } 76 77 public Link deleteLast(){ 78 Link temp = last; 79 if(first.next == null){ 80 first = null; 81 } 82 else{ 83 last.previous.next = null; 84 } 85 last = last.previous; 86 return temp; 87 } 88 89 //按照值進行刪除--可能存在找不到的時候 90 public Link delete(int key){ 91 Link current = first; 92 while(current.id != key ){ 93 current = current.next; 94 if(current == null){ 95 return null; 96 } 97 } 98 if(current == first){//find it at first item並非只有一個節點 99 first = current.next; 100 } 101 else{ //find it not first item 102 current.previous.next = current.next; 103 } 104 105 if(current == last){ //find it at last item 106 last = current.previous; 107 } 108 else{ //find it not last 109 current.next.previous = current.previous; 110 } 111 return current; 112 } 113 114 public void diaplayFirstToLast(){ 115 System.out.println("first to last"); 116 Link current = first; 117 while(current != null){ 118 System.out.print(current.id + " "); 119 current = current.next; 120 } 121 System.out.println(); 122 } 123 124 public void displayLastToFirst(){ 125 System.out.println("last to first"); 126 Link current = last; 127 while(current != null){ 128 System.out.print(current.id + " "); 129 current = current.previous; 130 } 131 System.out.println(); 132 } 133 }

雙向鏈表--Java實現