Saturday, October 19, 2013

Stack Implementation using a Linked List


#include <stdio.h>
#include <stdlib.h>

typedef struct _node {
    int data;
    struct _node *next;
} node;

struct Stack
{
    int count;
    node *top;
};

 struct Stack * createStack ()
{
    struct Stack *temp = (struct Stack *)
                         malloc(sizeof (struct Stack));
    if (!temp)
        return NULL;
    temp->count =0;
    temp->top=NULL;
    return temp;
}

int  push (struct Stack *stk, int data)
{
    node * newnode = (node *) malloc (sizeof (node));
    if (!newnode)
        return -1;
    newnode->data = data;
    newnode->next = stk->top;
    stk->count++;
    stk->top = newnode;
    printf("after pushing %d size of stack is %d\n",
            data,stk->count);
        return 0;
}

int isEmpty (struct Stack *stk)
{
  if (stk->count < 1 || !stk->top ) {
      printf("Stack empty\n");
      return 1;
  }
  return 0;
}


 int disp (struct Stack *stk)
{
    printf("******  displaying Stack *******\n");
    if (isEmpty(stk))
        return -1;
    node *trav = stk->top;
    while (trav){
        printf (" %d -> ",trav->data);
        trav = trav->next;
    }
    printf("NULL \n******  end Stack *******\n");
    return 0;
}
 int pop (struct Stack *stk)
{
    int data;
    if (isEmpty(stk))
        return -1;
    node *temp = stk->top;
    stk->top = stk->top->next;
    printf("popping %d\n",temp->data);
    data = temp->data;
    free (temp);
    stk->count--;
    return data;
}

 void deleteStack (struct Stack *stk)
{
    if (stk){
        while(stk->top){
            node *trav = stk->top;
            stk->top=trav->next;
            free(trav);
        }
    free (stk);
    }
}
int main ()
{
    struct Stack* myStack  = createStack();
    if (!myStack)
        printf("error aloocation\n");
    pop  (myStack);
    push (myStack,10);
    pop  (myStack);
    disp(myStack);
    push (myStack,10);
    push (myStack,1);
    disp(myStack);
    push (myStack,9);
    push (myStack,5);
    disp(myStack);
    pop  (myStack);
    deleteStack(myStack);
    return 0;
}

No comments:

Post a Comment