Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislukkk/795abf2fe2350f419594 to your computer and use it in GitHub Desktop.
Save chrislukkk/795abf2fe2350f419594 to your computer and use it in GitHub Desktop.
CareerCup_3.3 - SetOfStacks
package Chapter3;
public class Node<T> {
public T value;
public Node<T> next;
public Node(T d, Node<T> n){
value = d;
next = n;
}
}
package Chapter3;
import java.util.ArrayList;
import java.util.List;
public class SetOfStacks<T> {
private List<Stack<T>> stacks;
private int capacity;
public SetOfStacks(int c) {
stacks = new ArrayList<Stack<T>>();
capacity = c;
}
// go through all stacks and return size
public int size() {
int sz = 0;
for (int i = 0; i < stacks.size(); i++) {
sz += stacks.get(i).size();
}
return sz;
}
public void push(T value) {
if (stacks.size() == 0
|| stacks.get(stacks.size() - 1).size() >= capacity) {
// add one more stack if the current stack is full
stacks.add(new Stack<T>());
}
stacks.get(stacks.size() - 1).push(value);
}
public T pop() {
if (stacks.size() == 0)
return null;
Stack<T> s = stacks.get(stacks.size() - 1);
T res = s.pop();
// remove current stack if it's empty
if (s.size() == 0)
stacks.remove(stacks.size() - 1);
return res;
}
// simply pop that stack
// without fill in the empty space from the bottom of following stacks
public T popAt(int index) {
if (index >= stacks.size())
return null;
Stack<T> s = stacks.get(index);
T res = s.pop();
if (s.size() == 0)
stacks.remove(index);
return res;
}
public void printAll() {
for (int i = 0; i < stacks.size(); i++) {
Stack<T> s = stacks.get(i);
s.print();
}
}
public static void main(String[] args) {
SetOfStacks<Integer> setOfStacks = new SetOfStacks<>(5);
for (int i = 1; i <= 20; i++) {
setOfStacks.push(i);
}
for (int i = 1; i <= 5; i++) {
setOfStacks.pop();
}
setOfStacks.popAt(1);
setOfStacks.printAll();
System.out.println("Size after operations: " + setOfStacks.size());
}
}
package Chapter3;
public class Stack<T> {
private int size = 0;
public Node<T> top = null;
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void push(T value) {
Node<T> n = new Node<T>(value, top);
size++;
top = n;
}
public T pop() {
if (top == null)
return null;
T res = top.value;
top = top.next;
size--;
return res;
}
public void print() {
if(top == null) return;
Node<T> cur = top;
while(cur != null) {
System.out.print(cur.value + "; ");
cur = cur.next;
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment