一,栈的定义
♦ 栈:是限定在表尾进行插入或删除操作的线性表。
♦对栈来说,一般将表尾称为栈顶(top),表头端称为栈底(base)。不含元素的空表称为空栈。
♦ 栈的修改是按后进先出的原则进行的,因此,栈又称为后进先出的线性表。

二,栈的表示与实现
顺序栈:即栈的顺序存储结构是利用一组地址连续的存储单元依次存放自栈底到栈顶的数据元素,
同时附设指针top,初值指向栈底(top=0),每当插入一个新的栈顶元素指针top+1,同样的删
除一个栈顶元素top-1,因此非空栈中,指针始终指向栈顶元素的下一 个位置。
指针base为栈底指针,在顺序栈中,它始终指向栈底位置。
top=0,为空栈,top=stack.length,为栈满。
代码实现
1 /**
2 * 顺序栈代码实现
3 */
4 import java.util.*;
5 class SeqStack{
6 // 存储栈元素的数组
7 private int[] stack;
8 // 标识栈顶的位置
9 private int top;
10
11 // 默认构造,初始大小为10
12 public SeqStack() {
13 /*this.stack=new int[10]; //因为该栈的底层是数组
14 this.top=0;*/
15 this(10); //调用另一个构造函数
16 }
17
18 // 构造函数,用户指定栈的初始大小
19 public SeqStack(int size) {
20 this.stack=new int[size]; //因为该栈的底层是数组
21 this.top=0; //初始时,栈为空时,top指向stack[0]位
22 }
23
24 // 入栈操作
25 public void push(int val){ //入栈前先要对栈空间进行检测
26 if(this.stack.length==this.top) //因为top指向的是所填元素的下一位,所以当top值等于stack.length值时,则栈满。
27 { //栈满,若要继续存储元素,则要先进行扩容。
28 this.stack=Arrays.copyOf(this.stack,this.stack.length+1);
29 }
30 this.stack[top]=val; //因为top指向的是所填元素的下一位,所以此时top位为空,直接将val存储在stack[top]位。
31 this.top++; //填完元素之后,将top指向下一位。
32 }
33
34 // 出栈,并把出栈的元素返回
35 public void pop(int count){ //自定义打印长度count
36 int j=this.top;
37 for(int i=this.top-1;i>=(this.top-count);i--,j--) //打印一个元素,top减1
38 {
39 System.out.print(this.stack[i]+" ");
40 }
41 this.top=j;
42 System.out.println();
43 }
44 public int pop() { //默认出栈一个元素
45
46 //this.top--;
47 int val=this.stack[--this.top];
48 return val;
49
50 }
51
52 // 返回栈顶元素
53 public int top(){
54 if(empty()){ //先判断栈中是否有元素
55 return 00000000;
56 }else{
57 return stack[top-1];
58 }
59
60 }
61
62 // 判断栈空
63 public boolean empty(){
64
65 /* if(this.top==0)
66 {
67 return true;
68 //System.out.println("栈空");
69 }
70 return false;*/
71 return this.top==0; //返回Boolean型值
72 }
73
74 // 判断栈满
75 public boolean full(){
76 /*if(this.top==this.stack.length)
77 {
78 return true;
79 }
80 return false;*/
81 return this.top==this.stack.length; //返回Boolean型值
82 }
83
84 // 返回栈元素的个数
85 public int size(){
86 return this.top; //因为top指向栈顶元素下一位,且元素是从0位开始存储的
87 }
88
89 // 自定义栈元素的打印方式
90 //@Override
91 public String toString(int[] arr) {
92 String str=new String();
93 for(int i=this.top-1;i>=0;i--) //因为当栈不为空时,top指向的始终是栈顶元素的下一位
94 {
95 str=str+this.stack[i]+" " ; //用连接符的方式将数组中的数打印出来
96 }
97 return str;
98 }
99 }
100
101 /**
102 * 描述: 顺序栈代码测试
103 */
104
105
106
107
108 public class SeqStacktext {
109 public static void main(String[] args) {
110
111 SeqStack ss=new SeqStack(5); //新new一个栈(数组),jvm自动调用构造方法。
112 for(int i=0;i<5;i++)
113 {
114 ss.push(i+1); //入栈操作
115 }
116
117 System.out.println(ss.top()); //打印栈顶元素
118
119 if(ss.full()) //判断栈满
120 {
121 System.out.println("栈满!");
122 }
123 System.out.println(ss.size());
124 ss.pop(5); // 定义出栈元素个数
125 if(ss.empty()) //判断栈空
126 {
127 System.out.println("栈空!");
128 }
129 // ss.pop(); //默认出栈一个元素
130 }
131 }
运行结果:
