0
点赞
收藏
分享

微信扫一扫

线性表之堆栈的实现

Go_Viola 2023-04-27 阅读 70

1. /**
2.  * Stack.java
3.  * 线性表之栈
4.  * 栈的特点:
5.  * 先进后出
6.  * 即, 从头部加入(push)一个新数据
7.  *    从头部取出(pop)一个数据
8.  */
9. package
10.   
11. /**
12.  * @author sunxboy
13.  * 9:59:52 AM  May 22, 2007
14.  */
15. public class
16.   
17. int[] data;  
18. int
19. int
20. public Stack(int
21. this.maxSize = maxSize;  
22. new int[maxSize];  
23. 1;  
24.     }  
25.       
26. /**
27.      * 依次加入数据
28.      * @param data 要加入的数据通信
29.      * @return 添加是否成功
30.      */
31. public boolean push(int
32. if(top+1== maxSize) {  
33. "栈已满!");  
34. return false;  
35.         }  
36. this.data[++top] = data;  
37. return true;  
38.     }  
39.       
40. /**
41.      * 从栈中取出数据
42.      * @return 取出的数据
43.      */
44. public int pop() throws
45. if(top==-1) {  
46. throw new Exception("栈已空!");  
47.         }  
48. return this.data[top--];  
49.     }  
50.       
51. public static void main(String[] args) throws
52. new Stack(1000);  
53. 1);  
54. 2);  
55. 3);  
56. 4);  
57. 5);  
58. while(stack.top>=0)  
59.         {  
60.             System.out.println(stack.pop());  
61.         }         
62.     }  
63. }

举报

相关推荐

0 条评论