Operations
push(x)
Adds the element x at the top of the stack
pop()
Removes the element from the top of the stack and returns it
Returns an error if the stack is empty
peek()
Returns (but does not remove) the element at the top of the
stack
isEmpty()
Returns 1 if the stack is empty and 0 otherwise
Stack - Example
pop()
returns 13
push(13)
push(7)
13
pop()
peek()
returns 10 returns 10
peek()
returns 20
push(10)
10
10
10
10
pop()
returns 3
push(3)
push(20)
20
Stack Array-based
Implementation
#include <stdio.h>
T peek() {
if (isEmpty()) {
fprintf(stderr, "Error 103 - The stack is empty!\n");
T x;
return x;
}
return stackArray[topLevel]; }
int isEmpty() {
return (topLevel < 0); }
Stack() { // constructor
topLevel = -1; } // the stack is empty in the beginning
};
int main() {
Stack<int> s;
s.push(7); s.push(3); s.push(10); s.push(13); s.push(20);
s.push(9); s.push(1); printf("%d\n", s.pop());
printf("%d\n", s.peek()); printf("%d\n", s.peek());
printf("%d\n", s.pop()); printf("%d\n", s.peek());
s.push(100); printf("%d\n", s.pop());
return 0;
}
Paranthesis Checking
Given a string S composed of the characters (,
), [, ], {, } (round bracket, square bracket and
curly bracket), determine if the parantheses are
correctly balanced
S=([()[{([]()){}}[[]]]{}])[]({}) is correctly balanced
S1=([]({)}), S2=[{{}(())([]{, S3=[(){}]] are not
correctly balanced
Algorithm
We use a stack
We traverse the string from left to right
We push on the stack every open bracket
For every closed bracket, the bracket at the top of the stack
must be an open bracket of the same type (and the stack must
not be empty) => then we pop the open bracket from the stack
In the end, the stack must be empty
stk.pop();
}
}