A stack is a one-ended linear data structure which models a real world stack by having two primary operations, namely push and pop.
pop();
push('Onion');
push('Celery');
push('Waltermelon');
pop();
pop();
push('Lettuce');
Name | Big O Notation |
---|---|
Pushing | O(1) |
Popping | O(1) |
Peeking | O(1) |
Searching | O(n) |
Size | O(1) |
Brackets | Valid or Not? |
---|---|
[ { } ] | Valid |
( ( ) ( ) ) | Valid |
{ ] | Invalid |
[ ( ) ] ) ) ( ) | Invalid |
[ ] { } ( { } ) | Valid |
xxxxxxxxxx
Let S be a stack
For bracket in bracket_string:
rev = getReversedBracket(bracket)
If isLeftBracket(bracket):
S.push(bracket)
Else If S.isEmpty() or S.pop() != rev:
return false // Invalid
return S.isEmpty() // Valid if S is empty
Instructions
xxxxxxxxxx
push(4);
push(2);
push(5);
push(13);
Instructions
xxxxxxxxxx
pop();
pop();
pop();
pop();
ximport java.util.LinkedList;
public class Stack <T> implements Iterable <T> {
private LinkedList <T> list = new LinkedList <T>();
public Stack() { }
public Stack(T firstElem) {
push(firstElem);
}
public int size() {
return list.size();
}
public boolean isEmpty() {
return size() == 0;
}
public void push(T elem) {
list.addLast(elem);
}
public T pop() {
if (isEmpty()) {
throw new java.util.EmptyStackException();
}
return list.removeLast();
}
public T peek() {
if (isEmpty()) {
throw new java.util.EmptyStackException();
}
return list.peekLast();
}
public java.util.Iterator <T> iterator() {
return list.iterator();
}
}