栈和队列的原理想必大家都懂,非常简单,一个后进先出,一个先进先出,话不多说,看代码
栈
public class Stack {
private int[] arr;
private int top;//栈顶元素下标
private int size;
public Stack(int size) {
this.size = size;
arr = new int[size];
top = -1;
}
public void push(int element) {//进栈
if(isFull()) {
System.out.println("栈满了,进栈失败");
}else {
arr[++top] = element;
}
}
public int pop() {//出栈
if(isEmpty()) {
System.out.println("栈空,出栈失败");
return -1;
}else {
return arr[top--];
}
}
public int peek() {//返回栈顶元素
if(isEmpty()) {
//System.out.println("栈顶没有元素");
return -1;
}else {
return arr[top];
}
}
public boolean isFull() {
return (top == size - 1) ? true : false;
}
public boolean isEmpty() {
return (top == -1) ? true : false;
}
public void print() {//打印出栈顺序
while(peek() != -1) {
System.out.print(pop() + " ");
}
}
}
测试代码
public class TestAll {
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(5);
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(1);
System.out.print("出栈顺序为:");
stack.print();
}
}
循环队列
public class Queue {
private int[] arr;
private int maxSize;
private int front;//指向队头元素的下标
private int rear;//指向队尾元素的下标
public int length;
public Queue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
front = 0;
rear = -1;
length = 0;
}
public void enQueue(int element) {//进入队列
if(isFull()) {
System.out.println("队列已满");
}else {
if(rear == maxSize - 1) {
rear = -1;
}
arr[++rear] = element;
length++;
}
}
public int deQueue() {//返回队首元素并删除
if(isEmpty()) {
System.out.println("队列为空");
return -1;
}else {
int element = arr[front++];
if(front == maxSize) {
front = 0;
}
length--;
return element;
}
}
public boolean isFull() {
return (length == maxSize) ? true : false;
}
public boolean isEmpty() {
return (length == 0) ? true : false;
}
public void print() {//打印队列
while(!isEmpty()) {
System.out.print(deQueue() + " ");
}
System.out.println();
}
}
测试代码
public class TestAll {
public static void main(String[] args) {
Queue queue = new Queue(5);
queue.enQueue(1);
queue.enQueue(2);
queue.enQueue(3);
queue.enQueue(4);
queue.enQueue(5);
System.out.print("队列顺序为: ");
queue.print();
}
}
重新实现一下,帮助自己巩固一下以前的学习,接下来继续实现链表和二叉树去咯