数组栈:java
public class ArrayStack { private Integer[] arr; private Integer index; public ArrayStack(int initSize) { if(initSize < 0) { throw new IllegalArgumentException("this init size is less than 0"); } arr = new Integer[initSize]; index = 0; } public Integer peek() { if(index == 0) { return null; } return arr[index - 1]; } public void push(int obj) { if(index == arr.length) { throw new ArrayIndexOutOfBoundsException("this stack is full"); } arr[index++] = obj; } public Integer pop() { if(index == 0) { throw new ArrayIndexOutOfBoundsException("this stack is empty"); } return arr[--index]; } public static void main(String[] args) { ArrayStack stack = new ArrayStack(5); stack.push(5); stack.push(3); System.out.println(stack.pop()); stack.pop(); System.out.println(stack.peek()); } }
运行结果:
数组队列:数组
public class ArrayQueue { private Integer[] arr; private Integer size; private Integer first; private Integer last; public ArrayQueue(int initSize) { if(initSize == 0) { throw new IllegalArgumentException("this is queue is less than 0"); } arr = new Integer[initSize]; size = 0; first = 0; last = 0; } public Integer peek() { if(size == 0) { return null; } return arr[first]; } public void push(int obj) { if(size == arr.length) { throw new ArrayIndexOutOfBoundsException("this queue is full"); } size++; arr[last] = obj; last = last == arr.length - 1 ? 0 : last + 1; } public Integer poll() { if(size == 0) { throw new ArrayIndexOutOfBoundsException("this queue is empty"); } size--; int tmp = first; first = first == arr.length - 1 ? 0 : first + 1; return arr[tmp]; } public static void main(String[] args) { ArrayQueue queue = new ArrayQueue(5); queue.push(4); queue.push(6); System.out.println(queue.poll()); System.out.println(queue.peek()); } }
运行结果:less
取栈中最小元素:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操做getMin。要求以下:ide
pop、push、getMin操做的时间复杂度都是O(1)。 设计的栈类型可使用现成的栈结构。 思路:使用两个栈,stack2栈顶元素维持stack1中最小元素的值,当入栈的元素小于stack2栈顶元素时直接入satck2,不然取栈顶元素的值再入satck2.
import java.util.Stack; public class work3 { private Stack<Integer> stack1; private Stack<Integer> stack2; public work3() { this.stack1 = new Stack<Integer>(); this.stack2 = new Stack<Integer>(); } public void push(int num) { if(this.stack2.isEmpty()) { this.stack2.push(num); }else if(num < this.getMin()) { this.stack2.push(num); }else { int newNum = this.stack2.peek(); this.stack2.push(newNum); } this.stack1.push(num); } public int pop() { if(this.stack1.isEmpty()) { throw new RuntimeException("You stack is empty."); } this.stack2.pop(); return this.stack1.pop(); } public int getMin() { if(this.stack2.isEmpty()) { throw new RuntimeException("You stack is empty."); } return this.stack2.peek(); } public static void main(String[] args) { work3 stack = new work3(); stack.push(5); System.out.println(stack.getMin()); stack.push(1); System.out.println(stack.getMin()); stack.pop(); stack.push(2); System.out.println(stack.getMin()); } }
运行结果:this