栈
一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。
栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据在栈顶。
用一个顺序表实现栈:
public class MyStack {
public int[] elem; //数组
public int top; //表示当前可以存放数据元素的下标
public MyStack() {
this.elem = new int[10];
}
public void push(int data) {
if (full()) {
this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
}
this.elem[this.top++] = data;
}
public boolean empty() {
return this.top == 0;
}
public boolean full() {
return this.top == this.elem.length;
}
public int pop() {
if (empty()) {
throw new RuntimeException("栈空!");
}
int data = this.elem[this.top-1];
this.top--;
return data;
}
public int peek() {
if (empty()) {
throw new RuntimeException("栈空!");
}
return this.elem[this.top-1];
}
public int size() {
return this.top;
}
}
队列
只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(FirstIn First Out) 。
入队列:进行插入操作的一端称为队尾(Tail/Rear)
出队列:进行删除操作的一端称为队头(Head/Front)
用一个链表实现队列:
class Node {
public int data;
public Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public Node(int data) {
this.data = data;
}
}
public class MyQueue {
public int usedSize;
public Node front;
public Node rear;
public boolean offer(int val) {
Node node = new Node(val);
if (this.rear == null) {
this.front = node;
this.rear = node;
}else {
this.rear.next = node;
this.rear = node;
}
this.usedSize++;
return true;
}
//出队且删除队头元素
public int poll() {
if (isEmpty()) {
throw new RuntimeException("队列为空!");
}
int data = this.front.data;
this.front = this.front.next;
return data;
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("队列为空!");
}
return this.front.data;
}
public boolean isEmpty() {
return this.usedSize == 0;
}
public int size() {
return this.usedSize;
}
}
循环队列
数组实现环形队列:
public class MyCircularQueue {
public int[] elem;
public int front;
public int rear;
public MyCircularQueue(int k) {
this.elem = new int[k];
}
public boolean enQueue(int value) {
if (isFull()) {
return false;
}
this.elem[this.rear] = value;
this.rear = (this.rear+1)%this.elem.length;
return true;
}
public boolean deQueue() {
if (isEmpty()) {
return false;
}
this.front = (this.front+1)%this.elem.length;
return true;
}
public int Front() {
if (isEmpty()) {
return -1;
}
return this.elem[this.front];
}
public int Rear() {
if (isEmpty()) {
return -1;
}
int index = this.rear == 0 ? this.elem.length-1 : this.rear-1;
return this.elem[index];
}
public boolean isEmpty() {
return this.rear == this.front;
}
public boolean isFull() {
if ((this.rear+1)%this.elem.length == this.front) {
return true;
}
return false;
}
}