Showing posts with label DataStructure & Algorithm. Show all posts
Showing posts with label DataStructure & Algorithm. Show all posts

Saturday, February 15, 2014

Stack Implementation using Linked List

#include<iostream>
#include<string>
using namespace std;

//class for each node of stack
class Node{
    private:
        Node* nextNode;
        string data;
    public:
        friend class Stack;
};

//Stack Class
class Stack {
    private:
        Node* top;

    public:
        Stack() {
            top = NULL;
        }
        int push(string data);
        string pop();
        int traverse();
};

//push operation - insertion at top
int Stack::push(string data) {
    Node* temptr = new Node();
    temptr->data = data;
    //if not adding first node
    if(top != NULL) {
        temptr->nextNode = top;
    } else {
        temptr->nextNode = NULL;
    }
    top = temptr;
    return 0;
}

//pop operation -- deletion from top
string Stack::pop() {
    string data = top->data;
    Node* temptr = top;
    top = top->nextNode;
    delete(temptr);
    return data;
}

//traverse the stack elements
int Stack::traverse() {
    Node* temptr = top;
    while(temptr != NULL){
        cout<< temptr->data <<endl;
        temptr = temptr->nextNode;
    }
    return 0;
}

int main() {
    Stack* so = new Stack();
    so->push("abc");
    so->push("def");
    so->push("ghi");
    cout<<"Display Stack::\t"<<endl;
    so->traverse();
    cout<<"Popped Item::\t"<<so->pop()<<endl;
    cout<<"Display Stack::\t"<<endl;
    so->traverse();
}