栈和队列的实现
(1)栈
基本概念
- 栈:限制在一端进行插入和删除的线性表,first in last out – FILO的线性表;
- 栈顶(top):允许插入和删除的一端,又称为表尾;
- 栈底(bottom):表头;
- 空栈:栈内没有元素;
- 压栈:插入元素
- 弹栈:删除元素
基本运算:是否为空,进栈,出栈,读栈顶元素,销毁栈;
栈的顺序结构:
public class Stack {
private int size;
private Object[] elements;
private int ptr = -1;
public Stack() {
size = 100;
elements = new Object[100];
}
public Stack(int size) {
elements = new Object[size];
this.size = size;
}
public void push(Object element) throws Exception {
if (ptr > size - 1)
throw new Exception("stack over flow");
elements[++ptr] = element;
}
public Object pop() throws Exception {
if (ptr == -1)
throw new Exception("empty stack");
return elements[ptr--];
}
public Boolean isEmpty() {
if (ptr == -1)
return true;
return false;
}
}
链式实现
public class LinkStack<T> {
private static class Node<T>{
private T data;
private Node<T> nextNode;
public Node() {
}
public Node(T data) {
this.data = data;
}
}
private Node<T> top;
private int ptr = -1;
public LinkStack() {
}
public LinkStack(T element) {
top = new Node<T>(element);
}
public void push(T element) {
Node<T> node = new Node<>(element);
node.nextNode=top;
top = node;
ptr++;
}
public T pop() throws Exception {
if (ptr == -1)
throw new Exception("empty stack");
ptr --;
Node<T> popNode = top;
top = top.nextNode;
popNode.nextNode = null; //release ram
return popNode.data;
}
public Boolean isEmpty() {
if (ptr == -1)
return true;
return false;
}
}
(2)队列
基本概念
- 队列(queue):运算受限的线性表,first in first out (FIFO)的线性表,只允许表的一端删除,表的另一端插入;
- 队首(front):删除的一端;
- 队尾(rear):插入的一端;
- 空队列:无元素;
循环队列
把队列分配的内存空间看作一个首尾相接的圆,利用首尾指针(取名front,rear)去维护它;
front指向第一个元素的位置,rear指向队尾元素的下一个位置;
队列为空是 front = rear;
public class SequenceQueue<T> {
private Object[] elements;
private int size;
private int front = 0;
private int rear = 0;
public SequenceQueue(int size) {
this.size = size + 1;//因rear指向队尾的下一个位置(用于判空和判满),需要数组长度需+1;
elements = new Object[size + 1];
}
public void push(T t) throws Exception {
if (isFull())
throw new Exception("out of size ");
elements[rear] = t;
rear = (rear + 1) % size;
}
public T pop() throws Exception {
if (isEmpty())
throw new Exception("empty queue");
T reValue = (T) elements[front];
front = (front + 1) % size;
return reValue;
}
public boolean isFull() {
return (rear + 1) % size == front ? true : false;
}
public boolean isEmpty() {
return front == rear;
}
public int size() {
return this.size;
}
}
链式实现
可参照栈链式实现稍加修改;实现一个单链表即可;