Skip to content

Instantly share code, notes, and snippets.

@michaelniu
Created April 15, 2015 22:00
Show Gist options
  • Save michaelniu/f45cc3fd60d2f76b6ce4 to your computer and use it in GitHub Desktop.
Save michaelniu/f45cc3fd60d2f76b6ce4 to your computer and use it in GitHub Desktop.
cc150_3_3
/*
* 3.3 Imagine a (literal) stack of plates. If the stack gets too high, it might topple.
Therefore, in real life, we would likely start a new stack when the previous stack
exceeds some threshold. Implement a data structure SetOf Stacks that mimics
this. SetOf Stacks should be composed of several stacks and should create a
new stack once the previous one exceeds capacity. SetOf Stacks. push() and
SetOf Stacks. pop() should behave identically to a single stack (that is, popO
should return the same values as it would if there were just a single stack).
FOLLOW UP
Implement a function popAt(int index) which performs a pop operation on
a specific sub-stack.
Algorithm
Use Stack Of Stack to do it
for the Follow up use an array to store the every stack topnode
*/
public class StackSets_3_3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
class StackSet{
SingleStack topStack;
public StackSet(){
topStack = null;
}
public void push(int data ){
if(topStack.isFull()){
SingleStack newStack = new SingleStack();
newStack.next = topStack;
topStack = newStack;
}
topStack.push(data);
}
public int pop(){
if(topStack.top == null){
topStack = topStack.next;
}
if(topStack!=null){
return topStack.pop();
}
return -1;
}
}
class SingleStack{
final int CAPACITY =3;
SingleStackNode top;
SingleStack next;
int total;
public SingleStack (){
top = null;
total = 0;
}
public void push(int data){
if(total ==CAPACITY )
return;
SingleStackNode newNode = new SingleStackNode(data);
if (top == null){
top = newNode;
}
else{
newNode.next=top;
top = newNode;
}
}
public boolean isFull(){
return total == CAPACITY;
}
public int pop(){
if(top !=null){
SingleStackNode popNode = top;
top = top.next;
return popNode.data;
}
return -1;
}
}
class SingleStackNode{
int data;
SingleStackNode next;
public SingleStackNode(int data){
this.data = data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment