Stack Data Structures
Stack Data Structures
Spring 2012
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
• The axioms are given implicitly – they determine the
expected behavior of the stack for a given sequence of
operations
– See the examples on the upcoming slides
Stack - Example
pop()
returns 13
peek() pop()
push(13) 13
returns 10 returns 10
pop() peek()
push(10) 10 10 10 10 returns 3 returns 20
push(3) 3 3 3 3 3 3 20
push(20)
push(7)
7 7 7 7 7 7 7 7 7
Stack – Array-based
Implementation
#include <stdio.h> T peek() {
if (isEmpty()) {
#define NMAX 100
fprintf(stderr, "Error 103 - The stack is empty!\n");
template<typename T> class Stack { T x;
private: return x;
T stackArray[NMAX]; }
int topLevel; return stackArray[topLevel]; }
public:
void push(T x) {
if (topLevel >= NMAX - 1) { int isEmpty() {
fprintf(stderr, "Error 101 - The stack is full!\n"); return (topLevel < 0); }
return;
} Stack() { // constructor
topLevel++;
stackArray[topLevel] = x; topLevel = -1; } // the stack is empty in the beginning
} };