The following example implements a stack as a structure with an array field. Unlike the previous automatic structure version, the dynamic version allocates the array dynamically on the heap with the new
operator. Surprisingly, the change requires few modifications to the previous version. The driver in both versions creates a stack structure object as an automatic variable. However, in the dynamic version, the data array is a pointer rather than an array, allowing the client program to specify the stack's size when creating it.
Construction | Typical Operations | Optional Operations | Destruction |
---|---|---|---|
dstack make_stack(int size) { dstack temp; temp.st = new char[size]; temp.sp = 0; temp.max = size; return temp; } void init_stack(dstack* s, int size) { s->st = new char[size]; s->sp = 0; s->max = size; } |
void push(dstack* s, char data) { if (s->sp < s->max) s->st[s->sp++] = data; else throw "Stack Overflow"; } char pop(dstack* s) { if (s->sp > 0) return s->st[--(s->sp)]; else throw "Stack Underflow"; } |
int size(dstack* s) { return s->sp; } char peek(dstack* s) { return s->st[s->sp - 1]; } |
void cleanup(dstack* s) { delete s->st; } |
new
, sets max, the maximum size of the stack, to size, and sets the stack pointer, sp, to 0new
Formatted with tab stops set at 8 spaces.
View | Download |
---|---|
dstack.h | dstack.h |
dstack.cpp | dstack.cpp |
dtest.cpp | dtest.cpp |