Sunday, November 1, 2020

Code of Stack in C Using Array

// stack using array


// library


#include<stdio.h>

#include<stdlib.h>


// make structure   maxsize , top , *items


struct stack{

int maxSize;

int top;

int *items;

};



// initialization

struct stack* newStack(int capacity){

    struct stack *p =  (struct stack *)malloc(sizeof(struct stack));


    p->maxSize  = capacity;

    p->top = -1;

    p->items = (int *)malloc(sizeof(int) * capacity);


    return p;

}



// operations for our stack


// top

int top(struct stack* p ){

    return p->items[p->top];

}


// isEmpty

int isEmpty(struct stack* p ){

    return p->top == -1;

}


// isFull


int isFull(struct stack *p){

    return p->top + 1 == p->maxSize;

}

// size


int size(struct stack * p){

    return p->top + 1;

}


// push

void push(struct stack* p , int element){    //        12 3  4 4 3

    if(isFull(p)){

        printf("Overflow!\n");

    }else{

        p->items[++p->top] = element;

    }

}


// pop


int pop(struct stack * p ){

    if(isEmpty(p)){

        printf("Underflow!");

    }else{

        return p->items[p->top--];

    }


}




int main(){

struct stack * s = newStack(5);


push(s,1);

push(s,5);

push(s,3);

push(s,6);


//   1    5     3   6


printf("%d\n",top(s));


printf("%d",size(s));



return 0;

}







No comments:

Post a Comment