栈的介绍
- 栈是一个先入后出的有序列表
- 栈中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)
- 根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除
栈的快速入门
用数组模拟栈的使用,由于栈是一种有序列表,当然可以使用数组的结构来存储栈的数据内容
数组模拟栈思路如下
- 定义一个top来表示栈顶,初始化为-1
- 入栈的操作,当有数组加入到栈式,top++,stack[top] = data;
- 出栈的操作,int value = stack[top]; top-- retrun value
代码如下
package day04;
import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
//创建栈
ArrayStack stack = new ArrayStack(4);
String key = "";
boolean loop = true;
Scanner scanner = new Scanner(System.in);
while (loop){
System.out.println("(show)遍历栈");
System.out.println("(exit)退出栈");
System.out.println("(push)往栈中添加数据");
System.out.println("(pop)从栈中取出数据");
System.out.println("请输入你的选择");
key = scanner.next();
switch (key){
case "show":
stack.showStack();
break;
case "exit":
loop = false;
break;
case "push":
System.out.println("请输入往栈中添加的数据");
int value = scanner.nextInt();
stack.push(value);
break;
case "pop":
try {
int num = stack.pop();
System.out.printf("从栈中取出的数据为%d\n",num);
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
}
}
class ArrayStack{
public int maxSize; //栈的大小
public int[] stack; //使用数组来模拟栈
public int top = -1; //表示的是栈顶
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
//判断是栈是否满了
public boolean isFull(){
return top == maxSize-1;
}
//判断栈是否为空
public boolean isEmpty(){
return top==-1;
}
//入栈
public void push(int value){
if (isFull()){
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
//出栈
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈里面没有数据了~");
}
int value = stack[top];
top--;
return value;
}
//遍历栈
public void showStack(){
if (isEmpty()){
System.out.println("栈空");
return;
}
for (int i = top; i >=0 ; i--) {
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
}
Java中的栈
java本身就带有了栈这个数据结构,代码如下
public class 栈{
public static void main(String[] args) {
Stack<Integer> sta=new Stack<>();
//往栈中添加元素
sta.push(1);
sta.push(2);
sta.push(3);
//查询当前元素距离栈顶的距离
System.out.println(sta.search(1));//3 栈底
System.out.println(sta.search(2));//2
System.out.println(sta.search(3));//1 栈顶
//获取当前栈顶值
System.out.println(sta.peek());
//获取当前栈顶值,并删除当前栈顶
System.out.println(sta.pop());
System.out.println(sta.pop());
System.out.println(sta.pop());
//获取栈中元素的个数
System.out.println(sta.size());
}
}
Deque 接口也提供了 对栈结构的操作。代码如下
public class 栈{
public static void main(String[] args) {
Deque<Integer> sta=new ArrayDeque<>();
//往栈中添加元素
sta.push(1);
sta.push(2);
sta.push(3);
//获取当前栈顶值
System.out.println(sta.peek());
//获取当前栈顶值,并删除当前栈顶
System.out.println(sta.pop());
System.out.println(sta.pop());
System.out.println(sta.pop());
//获取栈中元素的个数
System.out.println(sta.size());
}
}