現在常用的數據結構分為線性結構和非線性結構,而線性結構包括表,棧,隊列,非線性包括樹,圖等等。按照數據存儲方式有可以將表分為順序表和鏈表,棧分為順序棧,鏈棧,隊列也可以有鏈是隊列。在高級語言中通常用數組來表示順序存儲結構,所以表,棧,隊列都可以用數組來做。
1 package arrayList; 2 3 import java.util.Arrays; 4 import java.util.Date; 5 6 /** 7 * 順序表ArrayList,用數組表示。一組連續的地址空間 8 * @author LH-PC 9 * @param <E> 10 */ 11 public class ArrayList<E> { 12 private Object[] data = null; //data 用來保存此線性表的數據域 13 private int length; //線性表的容量 14 private int current; //實際表長 15 16 /** 17 * 默認將大小設置為10 18 */ 19 public ArrayList(){ 20 this(10); 21 } 22 23 24 /** 25 * 初始化線性表,聲明數組大小 26 * @param initialSize 數組大小 27 */ 28 public ArrayList(int initialSize){ 29 if(initialSize >= 0){ 30 this.length = initialSize; //設置線性表容量 31 this.data = new Object[initialSize]; //初始化數組 32 this.current = 0; //下標設置為0 33 }else { 34 throw new RuntimeException("初始化大小不能小於0:" + initialSize); //異常提示 35 } 36 37 } 38 39 40 /** 41 * 在線性表末尾添加元素,添加之前判斷線性表是否已經滿了 42 * @param e 添加的元素 43 * @return 成功返回真 44 */ 45 public boolean add(E e){ 46 //判斷是否已滿 47 ensureCapacity(); 48 //將元素添加到數組末尾 49 this.data[current++] = e; 50 // ++current; //下標++ 51 return true; 52 } 53 54 /** 55 * 刪除指定位置的元素 56 * @param index 57 * @return 58 */ 59 public boolean removeToIndex(int index){ 60 //刪除數組的元素:使用改變數組下標的方式達到刪除的效果。 61 //遍歷數組匹配指定下標,讓指定下標右邊的元素往左移動改變下標。最后再將最右邊的下標刪除 62 //a b c 63 //0 1 2 64 //data[index] = data[index + 1]; //改變右邊下標 65 //data //刪除最右邊的下標 66 //從待刪除下標處開始遍歷,將右邊的元素往左移 67 if(index >= current){ //如果index大於最大長度,返回假 68 System.err.print(new Date() + ": 下標超出表長"); 69 return false; 70 } 71 for (int i = index; i < current - 1; i++) { 72 data[i] = data[i+1]; //該表元素下標 73 } 74 data[current-1] = null; //將原來下標最右邊的一位元素變成null 75 --current; //實際表長-1 76 return true; 77 } 78 79 80 /** 81 * 根據下標返回元素值 82 * @param index 83 * @return 84 */ 85 public E get(int index){ 86 if(index >= 0){ 87 return (E) data[index]; 88 }else { 89 throw new RuntimeException("下標不能小於0:" + index); 90 } 91 } 92 93 /** 94 * 判斷表容量是否超出預定大小,如果超出將自動擴充容量 95 * 96 */ 97 public void ensureCapacity(){ 98 //判斷表實際長度是否超出表最大容量 99 if(current >= length){ 100 length *= 2; //將表最大容量*2 101 data = Arrays.copyOf(data, length); //將原數組進行拷貝 102 } 103 104 } 105 106 107 /** 108 * 返回順序表實際表長 109 * @return 110 */ 111 public int size(){ 112 return this.current; 113 } 114 115 /** 116 * 返回表容量 117 * @return 118 */ 119 public int length(){ 120 return this.length; 121 } 122 123 /** 124 * 125 * 判斷表是否為空 126 * @param args 127 */ 128 public boolean isEmpty(){ 129 //return (current == 0) ? true : false; 130 return current == 0; //如果current == 0,說明為空返回真,否則返回假 131 } 132 133 //主方法測試 134 public static void main(String[] args) { 135 ArrayList<Integer> list = new ArrayList<Integer>(); //創建arrayList 136 for (int i = 1; i <= 22; i++) { 137 list.add(i); 138 } 139 list.removeToIndex(0); 140 // list.removeToIndex(list.size()); 141 //遍歷list數組 142 for (int i = 0; i < list.size(); i++) { 143 System.out.println(list.get(i)); 144 } 145 146 } 147 148 }