Wednesday, November 6, 2019

Simple Stack Implementation

struct  stack
{
    int data;
    struct stack* next;

};

struct stack* tos=nullptr;

struct stack* getNewNode(const int d)
{
    struct stack* newNode= (struct stack* )malloc(sizeof(struct stack));
    if(!newNode)
    {
        std::cout<<"Unable to allocate memory\n";
        exit(0);
    }
newNode->data=d;
newNode->next=nullptr;
return newNode;
}

void push(struct stack** aTos, int data)
{
struct stack*node=getNewNode(data);
node->next=(*aTos);
(*aTos)=node;
}

bool stackEmpty()
{
    return (tos)?true:false;

}
struct stack* pop()
{
    if(!stackEmpty())
    {
        std::cout<<"Stack is empty\n";
        exit(0);
    }
    struct stack* temp=tos;
    tos=tos->next;
    return temp;
}

No comments:

Post a Comment