栈(stack)
线性数据结构;先入先出(first in last out 即FILO),先放入的在栈底(bottom),后放入的在栈顶(top)。
操作
入栈(push)和出栈(pop)
入栈(push)
出栈(pop)
实现方式
链表和数组两种
1.数组实现
声明一个固定大小的数组arr
入栈
将索引index指向0位置
压入数据的时候,先给arr[index]赋值
index++
如果index=arr.length的时候,用户要入栈,给用户抛出“栈已满”的异常
出栈
先将index–
再将arr[index]返回
查看栈顶的数据,不是出栈的话,只需要将arr[index-1]返回就行,但是不要添加index–功能(查看的时候,也需要先判断有没有数据,即index是否为0)
代码
public class ArrayStack {
private Integer[] arr; //数组
private Integer index; //指针
//构造函数
public ArrayStack(int stackSize) {
if (stackSize < 0) {
throw new IllegalArgumentException("初始化大小不能小于0");
}
//初始化数组,并将指针指向索引0位置
arr = new Integer[stackSize];
index = 0;
}
//向栈中存入数据
public void push(int num){
if(index==arr.length){
throw new IllegalArgumentException("栈已满");
}
arr[index]=num;
index++;
}
//从栈中弹出数据
public Integer pop(){
if(index==0){
throw new IllegalArgumentException("栈目前为空");
}
index--;
return arr[index];
}
//查看目前栈顶数据
public Integer peek(){
if(index==0){
return null;
}
return arr[index-1];
}
}
例如:
2.链表实现
入栈
出栈
代码
public class F {
private SNode s;
public class SNode{
int data;
SNode next;
}
F(){
s = null;
}
//入栈
public void push(int e){
SNode p = new SNode();
p.data = e;
p.next = s;
s = p;
}
//出栈
public int pop(){
if(s == null){
return -1;
}
SNode p = s;
s = s.next;
return p.data;
}
public int getTop(){
if(s == null){
return -1;
}
return s.data;
}
public static void main(String[] args) {
F f = new F();
System.out.println("链栈初始化成功!");
f.push(5);
f.push(4);
f.push(3);
f.push(2);
f.push(1);
System.out.println("创建成功");
System.out.println("元素依次出栈");
while(f.s!=null){
System.out.print(f.getTop()+" ");
f.pop();
}
System.out.println();
}
}