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

雙端鏈表--Java實現

args blog emp del pla bool spa public isp

 1 /*雙端鏈表--比普通鏈表多了一個指向最後一個節點的引用
 2  * 特點: 鏈表可以進行尾巴插入--輸出順序和輸入順序一致
 3  *      但是不可以進行尾巴刪除因為沒有倒數第二節點的引用
 4  * */
 5 public class MyFirstAndLastLinkedList {
 6     public Link first;
 7     public Link last;
 8     
 9     public MyFirstAndLastLinkedList() {
10         first = null;
11         last = null
; 12 } 13 14 public boolean isEmpty(){ 15 return first == null; 16 } 17 18 //頭插入的時候註意空鏈表對last的處理 19 public void insertFirst(int key){ 20 Link newLink = new Link(key); 21 if(isEmpty()){ 22 last = newLink; 23 } 24 newLink.next = first;
25 first = newLink; 26 } 27 28 //尾插入的時候註意空鏈表對first的處理 29 public void insertLast(int key){ 30 Link newLink = new Link(key); 31 if(isEmpty()){ 32 first = newLink; 33 } 34 else{ 35 last.next = newLink; 36 } 37 last = newLink;
38 } 39 40 //刪除註意只有一個節點對last的處理 41 public Link deleteFirst(){ 42 Link temp = first; 43 if(first.next == null){ 44 last = null; 45 } 46 first = first.next; 47 return temp; 48 } 49 50 public void displayLinkedList(){//順鏈打印 51 //System.out.println("first---to----last"); 52 Link current = first; 53 while(current!= null ){ 54 current.diaplayLink(); 55 System.out.print(""); 56 current = current.next; 57 } 58 System.out.println(); 59 } 60 61 //測試該類 62 public static void main(String[] args) { 63 int[] arr = {1,2,3,4,5,6}; 64 MyFirstAndLastLinkedList m = new MyFirstAndLastLinkedList(); 65 66 for(int i = 0; i < arr.length; i++){ 67 m.insertLast(arr[i]); 68 } 69 m.displayLinkedList(); 70 71 72 } 73 74 }

雙端鏈表--Java實現