栈是一种后进者先出,先进者后出的数据结构。可以理解成一摞叠在一起的盘子。我们平时放盘子的时候,都是从下往上一个一个放;取的时候,我们也是从上往下一个一个地依此取。
栈是一种“操作受限”的线性表,只允许在一端插入和删除数据。栈既可以用数组来实现,也可以用链表来实现。用数组实现的栈,叫做顺序栈,用链表实现的栈,叫链式栈。
//基于数据实现的顺序栈
public class StackBaseArray<T> {
private T[] data; //数据
private int count; //栈中元素个数
private int n; //栈的大小
public StackBaseArray(int capacity){
data= (T[])new Object[capacity];
count=0;
n=capacity;
}
//入栈
public boolean push(T value){
if(count==n) return false; //栈空间已满,直接返回false
data[count++]=value; //将value 放到下标为count的位置,并且count加一
return true;
}
//出栈
public T pop(){
if(count==0) return null; //当栈中数量为0的时候返回空值
T ret=data[count-1]; //返回下标为count-1的数据元素,并且栈中元素个数count减一
--count;
return ret;
}
//测试
public static void main(String[] args) {
StackBaseArray<Integer> stack=new StackBaseArray<>(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(stack.pop()+" "+stack.pop());//输出5,4;
}
}
//基于链表的栈
public class StackBaseOnLinkedList {
private Node top=null;
//入栈
public void push(int value){
Node newNode=new Node(value,null);
//判断是否栈空
if(top==null){
top=newNode;
}else{
newNode.next=top;
top=newNode;
}
}
//出栈
public int pop(){
if(top==null) return -1;
int value=top.data;
top=top.next;
return value;
}
private static class Node{
private int data;
private Node next;
public Node(int data,Node next){
this.data=data;
this.next=next;
}
public int getData(){
return data;
}
}
public static void main(String[] args) {
StackBaseOnLinkedList stack=new StackBaseOnLinkedList();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(stack.pop()+" "+stack.pop());//输出5,4
}
}```
另外补充一下:内存中的堆栈和数据结构堆栈不是一个概念,可以说内存中的堆栈是真实存在的物理区,数据结构中的的堆栈是抽象的数据存储结构。
内存空间在逻辑上分为三部分:代码区、静态数据区和动态数据区,动态数据区又分为栈区和堆区。
代码区:存储二进制代码。
静态数据区:存储全局变量、静态变量、常量,常量包括final修饰的常量和String常量。系统自动分配和回收。
栈区:存储运行方法的形参、局部变量、返回值。由系统自动分配和回收
堆区:new一个对象的引用或地址存储在栈区,指向该对象存储在堆区中的真实数据。