數組棧: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