用数组模拟栈
package com.cwh.stack;
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack st = new ArrayStack(5);
st.push(5);
st.push(52);
st.push(13);
st.list();
st.pop();
System.out.println("------");
st.list();
}
}
class ArrayStack {
private int maxSize; //栈的大小
private int[] stack; //数组,数组模拟栈,数据就放在该数组
private int top = -1; //top表示栈顶,初始化为—1
//构造器
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
//栈满
public boolean isFull() {
return top == maxSize - 1;
}
//栈空
public boolean isEmpty() {
return top == -1;
}
//入栈—push
public void push(int value) {
//先判断栈是否满
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
//出栈——pop, 将栈顶的数据返回
public int pop() {
//先判断栈是否空
if (isEmpty()) {
throw new RuntimeException("栈空");
}
int value = stack[top];
top --;
return value;
}
//遍历栈
public void list() {
if (isEmpty()) {
System.out.println("栈空");
return;
}
for(int i = top; i >= 0; i --) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
232 用栈实现队列
思路
使用两个栈来模拟队列。
StackIn 和 StackOut
push时,使用StackIn接收
pop时,从StackOut出。
每次pop时,判断StackOut是否为空,如果为空,则一次性将StackIn内所有元素都push进StackOut中。然后再从StackOut中弹出。
题解
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
/** Initialize your data structure here. */
public MyQueue() {
stackIn = new Stack<>(); // 负责进栈
stackOut = new Stack<>(); // 负责出栈
}
/** Push element x to the back of queue. */
public void push(int x) {
stackIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
dumpstackIn();
return stackOut.pop();
}
/** Get the front element. */
public int peek() {
dumpstackIn();
return stackOut.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
// 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
private void dumpstackIn(){
if (!stackOut.isEmpty()) return;
while (!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
225 用队列实现栈
思路
将队列头部元素(除最后一个元素外)重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
题解
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
//每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
public void push(int x) {
queue.offer(x);
int size = queue.size();
//移动除了 A 的其它数
while (size-- > 1)
queue.offer(queue.poll());
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}