- 栈和队列也是基于List来实现的,限制比List更严格(操作更少)List比栈和队列更灵活。
Stack 栈:只支持三个核心操作:入栈,出栈,取栈顶元素(先进后出)。
Queue 队列:也是有三个核心操作:入队列,出队列,取队首(先进先出)。
public class MyStack {
//管理一些int元素,不考虑扩容问题
private int[] array = new int[100];
private int size = 0;
//入栈
public void push(int x) {
array[size] = x;
size++;
}
//取栈顶元素(最后进的那个)
public int peak() {
return array[size-1];
}
//出栈
public int pop() {
int ret = array[size-1];
size--;
return ret;
}
}
public class MyQueueByLinkedList {
//Node这个类叫做内部类,定义在某个类或者方法中的类
//static 效果就是:创建Node的实例不依赖于MyQueueByLinkedList这个类的实例
static class Node {
public int val;
Node next = null;
public Node(int val) {
this.val = val;
}
}
//创建一个链表,就得有头节点,此处head节点不是傀儡节点
//基于链表来实现队列,可以入队列从尾部插入,出队列从头删除;也可以入队列从头部插入,出队列从尾部删除
//无论是哪种实现方式,最好把头和尾都记录下来
private Node head = null;
private Node tail = null;
//此处按照尾部入队列,头部出队列的方式实现
//入队列(标准库中的队列,入队列的操作叫offer)
public void offer(int val) {
Node newNode = new Node(val);
if (head == null) {
head = newNode;
tail = newNode;
return;
}
//当前如果不是空链表
tail.next = newNode;
tail = tail.next;
}
//出队列
public Integer poll() {
//如果当前队列是空队列
if (head == null) {
return null;
}
int ret = head.val;
head = head.next;
if (head == null) {
//删除完当前元素后,队列变成了空队列
tail = null;
}
return ret;
}
//取队首元素
public Integer peek() {
if (head == null) {
return null;
}
return head.val;
}
}
2.循环队列
队列中的有效元素有两种情况:(1)head在tail之前 (2)tail在head之前
当head和tail重合时,有可能是队列为空,也有可能是满了。可以引入size标记空还是满。
public class MyQueueByArray {
private int[] array = new int[100];
//[head,tail)有效元素的范围,注意tail可能在head之前
private int head = 0;
private int tail = 0;
private int size = 0;//元素个数
//入队列
public void offer(int val) {
if (size == array.length) {
return;//队列满了,无法继续插入
}
//保证下标不能越界
array[tail] = val;
tail++;
//tail++之后如果超出了数组的有效范围,就从头开始
if (tail >= array.length) {
tail = 0;
}
size++;
}
//出队列
public Integer poll() {
if (size == 0) {
return null;
}
Integer ret = array[head];
head++;
if (head >= array.length) {
head = 0;
}
size--;
return ret;
}
//取队首元素
public Integer peak() {
if (size == 0) {
return null;
}
return array[head];
}
}
3.标准库中的stack为空时,再pop,peak都会抛出异常。
public class TestStack {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
int ret = stack.pop();
System.out.println(ret);
ret = stack.pop();
System.out.println(ret);
}
}