Showing posts with label stack. Show all posts
Showing posts with label stack. Show all posts

Tuesday, December 8, 2009

Implement a stack using a linked list

Implement a stack using a linked list

class Stack
{
public:
    Stack();
    ~Stack();
    void push( void *data );
    void *pop();
protected:
    // Element struct needed only internally
    typedef struct Element {
        struct Element *next;
        void *data;
    } Element;

    Element *head;
};

Stack::Stack() {
    head = NULL;
    return;
}

Stack::~Stack() {
    while( head ){
        Element *next = head->next;
        delete head;
        head = next;
    }
    return;
}

void Stack::push( void *data ){
    //Allocation error will throw exception
    Element *element = new Element;
    element->data = data;
    element->next = head;
    head = element;
    return;
}

void *Stack::pop() {
    Element *popElement = head;
    void *data;

    /* Assume StackError exception class is defined elsewhere */
    if( head == NULL )
        throw StackError( E_EMPTY );

    data = head->data;
    head = head->next;
    delete popElement;
    return data;
}

Tuesday, November 24, 2009

Implement a Queue using Stack

Implement a Queue using Stack

#include<iostream>
#include<vector>

using namespace std;

class Stack
{
    private:
        vector<int> theArray;
        int topElement;
    public:
        Stack()
        {
            topElement = -1;
        }
        bool push(int number)
        {
            theArray.push_back(number);
            topElement = theArray.back();
            return true;
        }
        int pop()
        {
            if(isEmpty())
                return -1000;
            else
            {
                int a = theArray.back();
                theArray.pop_back();
                topElement = theArray.back();
                return a;
            }
        }
        bool isEmpty()
        {
            if(theArray.empty())
                return true;
            else
                return false;
        }
        int top()
        {
            return topElement;
        }
        void displayStack()
        {
            for(int i=0; i<thearray.size(); i++)
            {
                cout<<" "<<thearray[i];
            }
          
        }
       
};


Stack s1,s2;


void enQueue(int number)
{
    s1.push(number);
}
int deQueue()
{
    if(s2.isEmpty())
    {
        while(!s1.isEmpty())
        {
           s2.push(s1.pop());
        }
    }
        return s2.pop();
}
void displayQueue()
{
    while(!s2.isEmpty())
    {
        s1.push(s2.pop());
    }
    s1.displayStack();
}
int main()
{
    enQueue(1);
    enQueue(2);
    cout << deQueue()<<endl;
    cout << deQueue()<<endl;
    cout << deQueue()<<endl;
    displayQueue();
    return 0;
}