Saturday, October 19, 2013

Design a Stack using araay and Dynamic array

#include <stdio.h>
#include <malloc.h>

struct mystack {
    int* data;
    int top;
    int size;
};


struct mystack* createStack (void )
{
    struct mystack *temp = (struct mystack *) 
                            malloc(sizeof(struct mystack));
    if (temp == NULL)
        return NULL ;
    temp->top =-1;
    temp->size = 1;
    temp->data = (int *) malloc (sizeof(int) * temp->size);
    return temp;
}

int isEmpty(struct mystack *stk)
{
    return(stk->top == -1);
}

int isFull(struct mystack *stk)
{
    return(stk->top == (stk->size)-1);
}

void expand (struct mystack *temp)
{
  printf("expanding ..curent size %d\n",temp->size);
  temp->size*=2;
  temp->data = (int *) realloc(temp->data,temp->size
                                * sizeof(int));
}

void disp(struct mystack* stk)
{
    int i =0;
    printf("\n***Total elements*** are %d \n"
                                     ,stk->top+1);
    for(i=0;i<=stk->top;i++)
        printf("%d   ",stk->data[i]);
    printf("\n************ \n");
}

void push (struct mystack *stk, int data)
{
    if (isFull(stk))
    {
        printf("Stack full\n");
        expand(stk);
    }
  stk->top++;
  printf("pushing %d in position %d\n",data,(stk)->top);
  (stk)->data[(stk)->top]=data;
}

int pop (struct mystack *stk)
{
    if (isEmpty(stk))
    {
        printf("empty stack\n");
        return -1;
    }
    int temp;
    temp = (stk)->data[(stk)->top];
  printf("popping %d from position %d\n",
                         temp,(stk)->top);
  (stk)->top--;
  return temp;
}

void deleteStack (struct mystack *stk)
{
    if (stk)
    {
        if (stk->data)
            free(stk->data);
        free(stk);
    }
}

int main (void )
{
    //create a stack
    struct mystack *stk = NULL;
    stk = createStack();
    if (stk == NULL)
        return -1;
    push(stk,10);
    push(stk,3);
    push(stk,7);
    disp(stk);
    pop(stk);
    push(stk,8);
    push(stk,4);
    pop(stk);
    push(stk,9);
    push(stk,89);
    push(stk,11111111);
    push(stk,49);
    pop(stk);
    disp(stk);
    deleteStack(stk);
    return 0;
}

No comments:

Post a Comment