String Stack

Dynamic String Stack

Design a class that stores strings on a dynamic stack. The strings should not be fixedin length. Demonstrate the class with a driver program.

Solution:

 StackTest.cpp

 #include <iostream>

#include “dynamic_stack.h”

using namespace std;

int main() {

//create a stack

dynamic_stack stack;

// push 5 items

cout << “Pushing 5 strings in stack…” << endl;

stack.push(“Hello”);

stack.push(“How”);

stack.push(“are”);

stack.push(“you”);

stack.push(“buddy”);

cout << “Size: ” << stack.stack_size() << endl;

// for 5 times

for(int i = 0; i < 5; i++) {

// print peek, pop and size

cout << “\nPeek: ” << stack.peek() << endl;

cout << “Pop:  ” << stack.pop() << endl;

cout << “Size: ” << stack.stack_size() << endl;

}

} 

dynamic_stack.h

#include <string>

using namespace std;

#define DEFAULT_SIZE 3; //start size of stack

class dynamic_stack {

public:

//creates a new empty stack

dynamic_stack() {

size = DEFAULT_SIZE;

stack = new string[size];

top = 0;

}

// to push an item to stack

// if stack if full, it is dynamically expanded

void push(string item) {

if (top == size) { //if full

//expand and copy previous elemenbts to new stack

string* expanded = new string[size * 2];

for (int var = 0; var < size; ++var) {

expanded[var] = stack[var];

}

// delete space used by previous stack

delete[] stack;

// update new stack and size

stack = expanded;

size *= 2;

}

// add item to stack

stack[top++] = item;

}

// pop

string pop() {

if (top == 0) //if no elements

return NULL;

else // return element at top – 1 and update top

return stack[–top];

}

// to get top element

// return NULL if empty

string peek() {

if (top == 0) //if empty

return NULL;

else

return stack[top – 1];

}

// returns number of elements in stack

int stack_size() {

return top;

}

private:

string* stack; //stores the stack in an array

int size; //total capacity of stack

int top; // top empty position in stack

};