栈
栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊有序线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。
特点是后入先出。最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除。
栈的应用
- 子程序的调用:在跳往子程序前,会先将下个指令的地址存到堆栈中,直到子程序执行完后再将地址取出,以回到原来的程序中。
- 处理递归调用:和子程序的调用类似,只是除了储存下一个指令的地址外,也将参数、区域变量等数据存入堆栈中。
- 表达式的转换[中缀表达式转后缀表达式]与求值(实际解决)。
- 二叉树的遍历。
- 图形的深度优先(depth 一 first)搜索法。
数组实现栈
class ArrayStack{
//容量
public int max;
public int[] stack;
//栈顶
public int top=-1;
public ArrayStack(int max){
this.max=max;
stack=new int[this.max];
}
//空
public boolean isEmpty(){
return top==-1;
}
//满
public boolean isFull(){
return top==max-1;
}
//入栈
public void push(int num){
if(isFull()){
System.out.println("栈满");
return;
}else {
top++;
stack[top]=num;
}
}
//出栈
public int pop(){
if(isEmpty()){
throw new RuntimeException("空栈");
}else {
int value=stack[top];
top--;
return value;
}
}
//展示
public void show(){
if(isEmpty()){
System.out.println("栈空");
}else {
for (int i = top; i >=0; i--) {
System.out.printf("stack[%d]:%d\n",i,stack[i]);
}
}
}
}
单链表利用头插法实现栈
class LinkedListStack{
public Stack head=new Stack(0);
public boolean isEmpty(){
return head.next==null;
}
//入栈-头插法
public void push(int num){
Stack node=new Stack(num);
node.next=head.next;
head.next=node;
}
//出栈
public int pop(){
if(isEmpty()){
throw new RuntimeException("空栈");
}else {
int value=head.next.no;
head.next=head.next.next;
return value;
}
}
//展示
public void show(){
if(isEmpty()){
System.out.println("空栈");
return;
}else {
Stack temp=head.next;
while (temp!=null){
System.out.println(temp.no);
temp=temp.next;
}
}
}
}
class Stack{
public int no;
public Stack next;
public Stack(int no){
this.no=no;
}
}