数据结构-栈

1、准备数据

本文所使用的数据结构如代码所示

1
2
3
4
5
6
7
8
9
10
class {
String name;
int age;
}

class Stack{
static final int MAXLEN = 100;
Data [] data = new Data [MAXLEN];
int top; //栈顶
}

2、初始化栈

1
2
3
4
5
6
7
8
9
10
11
Stack initStack(){
Stack res;
if((res = new Stack())==null){
System.out.println("申请内存失败");
return null;
}
else{
res.top = 0;
return res;
}
}

3、判断空栈、满栈

3-1判断空栈

1
2
3
4
5
boolean isEmpty(Stack tmp){
boolean res;
res = (tmp.top==0);
return res;
}

3-2判断满栈

1
2
3
4
5
boolean isFull(Stack tmp){
boolean res;
res = (tmp.top==MAXLEN);
return res;
}

4、清空栈、释放空间

4-1清空栈

1
2
3
void clearStack(Stack tmp){
tmp.top=0;
}

4-2释放空间

1
2
3
void freeStack(Stack tmp){
tmp = null;
}

5、入栈

1
2
3
4
5
6
7
8
void pushStack(Stack tmp, Data data){
if(tmp.top+1>MAXLEN){
System.out.println('栈满');
}
else{
tmp.data[++tmp.top] = data;
}
}

6、出栈

1
2
3
4
5
6
7
8
Data popStack(Stack tmp){
if(tmp.top == 0){
System.out.println('栈空');
}
else{
return tmp.data[tmp.top--];
}
}