一、栈的介绍
- 栈的英文是stack。
- 栈是一个先入后出(first in last out)的有序列表
- 栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行操作的特殊线性表,允许插入和删除的一端,称为栈顶(top),另一端为固定不变的一端,称为栈底(bottom)。
二、图解栈的入栈和出栈

三、数组模拟栈
思路分析图

代码实现
class Stack1{
public int maxSize; // 栈的容量
public int[] stack; // 栈
public int pop = -1; // 栈顶,默认为-1
public Stack1(int maxSize) {
super();
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
// 判断栈满
public boolean isFull() {
return pop == maxSize - 1;
}
// 判断栈空
public boolean isEmpty() {
return pop == -1;
}
// 入栈
public void push(int value) {
// 判断栈是否已满
if(isFull()) {
System.out.println("栈满,无法添加数据");
return;
}
pop++;
stack[pop] = value;
}
// 出栈
public int pop() {
// 判断栈是否为空
if(isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
int value = stack[pop];
pop--;
return value;
}
// 遍历栈
public void list() {
// 判断栈是否为空
if(isEmpty()) {
System.out.println("栈空,没有数据");
return;
}
for(int i = pop; i >= 0; i--) {
System.out.printf("stack[%d]=%d
", i, stack[i]);
}
}
// 查看栈顶
public int peek() {
// 判断栈是否为空
if(isEmpty()) {
System.out.println("栈空,没有数据");
return -1;
}
return stack[pop];
}
}
链表模拟栈
思路分析逻辑如上图
代码实现
// 使用单向链表模拟栈
class Stack2{
// 创建头节点
private HeroNode head = new HeroNode(0);
// 入栈
public void push(HeroNode hero) {
HeroNode temp = head;
while(true) {
if(temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = hero;
}
// 出栈
public void pop() {
if(head.next == null) {
System.out.println("栈为空");
return;
}
// 定义临时节点
HeroNode temp = head;
while(true) {
if(temp.next.next == null) {
break;
}
temp = temp.next;
}
temp.next = null;
}
// 遍历
public void list() {
if(head.next == null) {
System.out.println("栈为空");
return;
}
// 定义临时节点
HeroNode temp = head.next;
while(true) {
if(temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
// 查看栈顶
public HeroNode peek() {
if(head.next == null) {
System.out.println("栈为空");
return;
}
// 定义临时节点
HeroNode temp = head;
while(true) {
if(temp.next == null) {
break;
}
temp = temp.next;
}
return temp;
}
}
// 创建节点类
class HeroNode{
public int no;
public String name;
public String nickName;
public HeroNode next;
// 用来创建头节点
public HeroNode(int no) {
super();
this.no = no;
}
// 用来创建数据节点
public HeroNode(int no, String name, String nickName) {
super();
this.no = no;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
return "HeroNode [no=" + no + ", name=" + name + ", nickName=" + nickName + "]";
}
}