public class Array_to_Stack_and_Queue{
public static class ArrayStack{
private int[] arr;
private int index;
public ArrayStack(int initSize) {
if(initSize < 0) {
System.out.println("the init size is less than 0");
}
arr = new int[initSize];
index = 0;
}
public void push(int obj) {
if(index == arr.length) {
System.out.println("the stack is full");
}
arr[index++] = obj;
}
public int pop() {
if(index == 0) {
System.out.println("the stack is empty");
}
return arr[--index];
}
public int peek() {
if(index == 0) {
System.out.println("the stack is empty");
}
return arr[index - 1];
}
public void printStack() {
for(int i = index-1; i >=0; i--) {
System.out.println(arr[i]);
}
System.out.println("------");
}
}
public static class ArrayQueue{
private int[] arr;
private int size;
private int head;
private int tail;
public ArrayQueue(int initSize) {
if(initSize < 0) {
System.out.println("The init queue size is less then 0");
}
arr = new int[initSize];
size = 0;
head = 0;
tail = 0;
}
public void push(int obj) {
if(size >= arr.length) {
System.out.println("the queue is full");
return;
}
size++;
arr[tail] = obj;
tail = (tail == arr.length-1) ? 0 : tail + 1;
}
public int pop() {
if(size == 0) {
System.out.println("the queue is empty");
}
size--;
int temp = head;
head = (head == arr.length - 1) ? 0 : head + 1;
return arr[temp];
}
public int peek() {
if(size == 0) {
System.out.println("the queue is empty");
}
return arr[head];
}
}
public static void main(String[] args) {
ArrayStack stack1 = new ArrayStack(4);
ArrayQueue queue1 = new ArrayQueue(4);
stack1.push(1);
stack1.push(2);
stack1.push(3);
stack1.push(4);
queue1.push(1);
queue1.push(2);
queue1.push(3);
queue1.push(4);
}
}
【栈和队列】用数组结构实现大小固定的队列和栈
最新推荐文章于 2019-07-27 13:19:39 发布