Created
July 5, 2014 23:43
-
-
Save iwilbert/07aa98b1cccd43435eac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SetOfStack{ | |
private ArrayList<Stack<Integer>> lstStack; | |
private int capacity; | |
public SetOfStack(int n) { | |
this.capacity = n; | |
this.lstStack = new ArrayList<Stack<Integer>>(); | |
} | |
public void push(int val) { | |
if(lstStack.size() == 0 || lstStack.get(lstStack.size()-1).size() == capacity) { | |
Stack<Integer> stack = new Stack<Integer>(); | |
lstStack.add(stack); | |
} | |
lstStack.get(lstStack.size()-1).push(val); | |
} | |
public int pop() { | |
if(lstStack.size() == 0) { | |
throw new NoSuchElementException("stack underflow!"); | |
} | |
int idx = lstStack.size()-1; | |
Stack<Integer> stack = lstStack.get(idx); | |
int val = stack.pop(); | |
if(stack.size() == 0) | |
lstStack.remove(idx); | |
return val; | |
} | |
public int popAt(int idx) { | |
if(lstStack.size() == 0) | |
throw new NoSuchElementException("stack underflow!"); | |
if(idx >= lstStack.size()) | |
throw new NoSuchElementException("stack overflow!"); | |
Stack<Integer> stack = lstStack.get(idx); | |
int val = stack.pop(); | |
if(stack.size() == 0) | |
lstStack.remove(idx); | |
return val; | |
} | |
} |
jason51122
commented
Jul 6, 2014
- Consider to move next element to current stack after pop() operation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment