首页 > 编程语言 > 详细

数组实现栈和队列

时间:2020-04-29 00:02:33      阅读:67      评论:0      收藏:0      [点我收藏+]

/**
* 数组实现栈和队列
*/
public class ArrayToQueueAndStack {

public static class MyStack<T> {

public Object[] arr;

public int size;

public int limit;

public MyStack(int limit) {
this.arr = new Object[limit];
this.limit = limit;
}

public void push(T value) {
if (size == limit) {
System.out.println("the stack is full");
return;
}
arr[size++] = value;
}

public T pop() {
if (isEmpty()) {
System.out.println("the stack is empty");
return null;
}
return (T) arr[--size];
}

public boolean isEmpty() {
return size == 0;
}

}

public static class MyQueue<T> {

public Object[] arr;

public int pushIndex;

public int pollIndex;

public int size;

public int limit;

public MyQueue(int limit) {
this.arr = new Object[limit];
this.limit = limit;
}

public void push(T value) {
if (size == limit) {
System.out.println("the queue is full");
return;
}
arr[pushIndex] = value;
size++;
pushIndex = nextIndex(pushIndex);
}

public T poll() {
if (isEmpty()) {
System.out.println("the queue is empty");
return null;
}
T value = (T) arr[pollIndex];
size--;
pollIndex = nextIndex(pollIndex);
return value;
}

public boolean isEmpty() {
return size == 0;
}

private int nextIndex(int pushIndex) {
return ++pushIndex % limit;
}

}

}

/* 如有错误,欢迎批评指正 */

数组实现栈和队列

原文:https://www.cnblogs.com/laydown/p/12798221.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!