Implementation of Stack

Implementatio in C: Using Array

#include<stdio.h>
#include<stdlib.h>
struct stack
{
    int top;
    unsigned capacity;
    int* array;
};
struct stack* create(unsigned capacity)
{
    struct stack* stack = (struct stack*)malloc(sizeof(struct stack));
    stack->top = -1;
    stack->capacity = capacity;
    stack->array = (int*)malloc(capacity * sizeof(int));
    return(stack);
}
int isFull(struct stack* stack)
{
    return(stack->top == stack->capacity - 1);
}
int isEmpty(struct stack* stack)
{
    return(stack->top == -1);
}
void push(struct stack* stack, int data)
{
    if(isFull(stack))
        printf("Stack overflow");
    stack->array[++stack->top] = data;
    printf("\nPushed data on stack : %d\n",data);
}
int pop(struct stack* stack)
{
    if(isEmpty(stack))
        printf("Stack Underflow");
    return stack->array[stack->top--];
}
int peep(struct stack* stack)
{
    if(isEmpty(stack))
        printf("No element in stack");
    return stack->array[stack->top];
}
int main()
{
    struct stack* stack = create(100);
    push(stack,10);
    push(stack,20);
    push(stack,30);
    printf("\n%d popped from stack",pop(stack));
    printf("\n%d Top of stack",peep(stack));
    printf("\n%d popped from stack",pop(stack));
    return 0;
}

Implementation in C: Using LinkedList

#include<stdio.h>
#include<stdlib.h>
struct stack
{
   int data;
   struct stack* next;
};
struct stack* create(int data)
{
    struct stack* new = (struct stack*)malloc(sizeof(struct stack));
    new->data = data;
    new->next = NULL;
    return(new);
}
int isEmpty(struct stack* stack)
{
    return !stack;
}
void push(struct stack** root, int data)
{
    struct stack* Stack = create(data);
    Stack->next = *root;
    *root = Stack;
    printf("\n%d pushed onto stack",data);
}
int pop(struct stack** root)
{
    if(isEmpty(*root))
        printf("\n underflow");;
    struct stack* empty = *root;
    *root = (*root)->next;
    int popped = empty->data;
    free(empty);
    return popped;
}
int main()
{
    struct stack* root = NULL;
    push(&root,10);
    push(&root,20);
    push(&root,30);
    printf("\n%d popped from stack",pop(&root));
    printf("\n%d popped from stack",pop(&root));
    return 0;
}

Comments

Popular posts from this blog

Three mislabeled Jar

Difference between Macro And function