一、栈的定义
我们在软件应用,栈这种后进先出的数据结构应用是非常普遍的。比如你流浪上网时,不管什么浏览器都有一个后退键,你点击后可以按访问顺序的逆序加载浏览过的网页。比如你看着新闻好好的,突然看到 一个年薪百万的工作,你毫不犹豫点进去,跳转一看,这都是啥呀,具体内容不了了之。此时你还想继续回去看新闻,就可以点击右上角的后退键。即即使你从一个网页开始,连续点击十几个链接跳转,你点“后退”时,还是可以像历史倒退一样,回到之前浏览过的某个网页。
栈(stack)是限定在表尾进行插入和删除操作的线性表。
我们把允许插入和删除的一端称为栈顶(top),另一端称为栈底(bottom),不含任何数据元素的栈称为空栈。栈又称为后进先出(Last In First Out)的线性表,简称LIFO结构。
二、栈的使用
以上为栈中最常用的方法,下面我们就用链表来模拟实现栈
三、栈的模拟实现
public class Stack {
private static class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
}
}
public Stack() {
}
private Node head;
//将元素压入栈中
public int push(int val) {
Node node = new Node(val);
node.next = head;
head = node;
return val;
}
//将元素弹出栈中
public int pop() {
if (head == null) {
throw new RuntimeException("the stack is empty ! ");
}
int val = head.val;
head = head.next;
return val;
}
//获取栈顶元素
public int peek () {
if (head == null) {
throw new RuntimeException("the stack is empty ! ");
}
return head.val;
}
//回去栈中的元素个数
public int size () {
if (head == null) {
return 0;
}
int size = 0;
Node temp = head;
while (temp != null) {
size++;
temp = temp.next;
}
return size;
}
//判断栈是否为空
public boolean isEmpty() {
return head == null;
}
}