设想有一堆盘子,堆太高可能会倒下来。因此,现实生活中,盘子堆到一定高度时,我们就会另外堆一堆盘子。请事先设计SetOfStacks, 模拟这种行为。
SetOfStacks应该由多个栈组成,并且在前一个栈填满时新建一个栈。此外,SetOfStacks.push() 和SetOfStacks.pop()应该与普通栈的操作方法相同(也就是说,
pop()返回的值,应该跟只有一个栈时的情况一样)。
- import java.util.Stack;
- public class SetOfStacks {
- class stack {
- public void push(int v);
- public int pop();
- }
- //push and pop are both operated from the last stack, just pay attention if the last stack is empty or full
- public void push(int value) {
- Stack<E> last = getLastStack();
- if(last != null && !last.isFull()) {
- last.push(value);
- }
- else {
- Stack stack = new Stack(capacity);
- stack.push(value);
- stacks.add(stack);
- }
- }
- public int pop() {
- Stack last = getLastStack();
- int v = last.pop();
- if (last.size == 0 ) {
- stacks.remove(stacks.size() -1);
- }
- return -1;
- }
- }
进阶:实现一个popAt( int index)方法,根据指定的子栈,执行pop操作。
- public class SetOfStacks{
- ArrayList<MyStack2> stacks= new ArrayList<MyStack2>();
- int capacity,numOfStack;
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- }
- public void push(int val){
- MyStack2 last=getLastStack();
- if( last!= null &&! last.isFull())
- last.push( val);
- else{
- MyStack2 stack= new MyStack2( capacity);
- stack.push( val);
- stacks.add( stack);
- numOfStack++;
- }
- }
- public int pop(){
- MyStack2 last=getLastStack();
- int value= last.pop();
- if( last. size==0)
- stacks.remove( last); //移除
- return value;
- }
- /**
- * 思路:从栈1弹出元素时,移出栈2的栈底元素压入栈1中,随后将栈3的栈底元素压入栈2的栈顶……
- * (假定出最后一个栈外,其余栈都是满的)
- * index
- *
- */
- public int popAt(int index){
- return leftShift( index, true);
- }
- public int leftShift( int index, boolean removeTop){
- MyStack2 stack= stacks.get( index);
- int removedItem;
- if( removeTop)
- removedItem= stack.pop();
- else
- removedItem= stack.removeBottem();
- if( stack.isEmpty()){
- stacks.remove( stack);
- } else if(! stacks.get( index+1).isEmpty()){
- int v=leftShift( index+1, false);
- stack.push( v);
- }
- return removedItem;
- }
- public MyStack2 getLastStack() {
- // TODO Auto-generated method stub
- return stacks.get( numOfStack-1);
- }
- }
- class MyStack2{
- private int capacity;
- public Node top,bottem;
- public int size;
- public MyStack2( int capacity){
- this. capacity= capacity;
- }
- public boolean isFull(){
- return capacity== size;
- }
- public void join(Node above,Node below){
- if( below!= null)
- below. above= above;
- if( above!= null)
- above. below= below;
- }
- public boolean push(int value){
- if( size>= capacity)
- return false;
- size++;
- Node n= new Node( value);
- if( size==1)
- this. bottem= n;
- join( n, this. top);
- top= n;
- return true;
- }
- public int pop(){
- Node n= top;
- top= top. below;
- size--;
- return n. data;
- }
- public boolean isEmpty(){
- return size==0;
- }
- public int removeBottem(){
- Node b= bottem;
- bottem= bottem. above;
- if( bottem!= null)
- bottem. below= null;
- size--;
- return b. data;
- }
- }