栈:
通俗理解:对于一个数组的插入和删除来讲,栈就像是一个盒子一样,所插入进来的数据都是先进后出,删除的数据都是后进先出;
画图理解:这样子画应该很好理解了吧,所有的数据都像是盒子的形式一样存贮和释放;
直接上代码:
创建一个栈;
1 package inn; 2 /** 3 * 栈 4 * @author caizhou 5 * 6 */ 7 8 public class myStack { 9 10 private long[] arr; 11 private int top; 12 13 public myStack(){ 14 arr =new long[20]; 15 top = -1; 16 } 17 18 public myStack(int maxsize){ 19 arr = new long[maxsize]; 20 top = -1; 21 } 22 23 /** 24 * 添加数据; 25 * @param value 26 */ 27 public void insert(long value){ 28 arr[++top] = value; 29 } 30 31 /** 32 * 移除数据。 33 */ 34 public long pop(){ 35 return arr[top--]; 36 } 37 38 /** 39 * 查看数据 40 */ 41 42 public long peek(){ 43 return arr[top]; 44 } 45 /** 46 * 判断是否为空; 47 * @return 48 */ 49 public boolean isEmpty(){ 50 return top==-1; 51 } 52 /** 53 * 判断是否溢出; 54 * @return 55 */ 56 public boolean isFull(){ 57 return top == arr.length -1; 58 } 59 }
测试栈:
1 package inn; 2 3 public class testStack { 4 public static void main(String[] args) { 5 6 myStack my = new myStack(4); 7 my.insert(23); 8 my.insert(12); 9 my.insert(21); 10 my.insert(60); 11 12 while(!my.isEmpty()){ 13 System.out.println(my.pop()); 14 } 15 } 16 }
测试结果:
60 21 12 23
队列:
通俗理解:队列,和栈基本上是完全相反的,对于数组的插入和删除来讲,队列就像是在电影院排队一样,先进先出,后进后出;
画图理解:符合先进先出,后进后出的理念;
直接上代码:
创建队列;
1 package inn; 2 /** 3 * 队列 4 * @author caizhou 5 * 6 */ 7 public class myQueue { 8 9 private long[] arr; 10 /** 11 * 总长度,队头,队尾 12 */ 13 private int element; 14 private int front; 15 private int end; 16 17 public myQueue(){ 18 arr = new long[20]; 19 element = 0; 20 front = 0; 21 end = -1; 22 23 } 24 public myQueue(int maxsize){ 25 arr = new long[maxsize]; 26 element = 0; 27 front = 0; 28 end = -1; 29 } 30 31 public void insert (int value){ 32 arr[++end] = value; 33 if(end == arr.length-1){ 34 end = -1; 35 } 36 element++; 37 } 38 39 public long delete(){ 40 long value = arr[front++]; 41 if(front ==arr.length){ 42 front =0; 43 } 44 element--; 45 return value; 46 } 47 48 /** 49 * 从队头查看数据; 50 * @return 51 */ 52 public long peek(){ 53 if(front ==arr.length){ 54 front =0; 55 } 56 return arr[front]; 57 } 58 59 public Boolean isEmpty(){ 60 return element ==0; 61 } 62 public boolean isFull(){ 63 return element ==arr.length-1; 64 } 65 }
测试队列:
package inn; public class testMyQueue { public static void main(String[] args) { myQueue my = new myQueue(4); my.insert(23); my.insert(32); my.insert(13); my.insert(53); System.out.println(my.peek()); while(!my.isEmpty()){ System.out.print(my.delete() + ","); } my.insert(10); // while(!my.isEmpty()){ // System.out.print(my.delete() + ","); // } System.out.println(my.peek()); } }
测试结果:
23 23,32,13,53,10
到此,栈和队列就讲完了,希望可以帮大家理解的清楚;