Stack implementation in C

              Stack is a primitive data structure which has a principle of LIFO (Last In First Out).It means the last element inserted in the stack will be coming first out. Stack data structure is very much useful in memory management, expression evaluation, towers of Hanoi problem and so on.

Let us implement Stack in C language as array.

Basic Operations of the Stack are

  • ‘push()’ – To insert a data
  • ‘pop()’ – To Delete a data
  • ‘peek()’ -It makes you to view the top data without deleting it.
  • ‘isEmpty()’-  It checks for Stack emptiness.
  • ‘isFull()’- It checks for Stack is full or not.

Variable:  A pointer variable is called top.

C Program:

#include <stdio.h>

#define MAX 12

int stack[MAX];

int top = -1;

// let us Check if the stack is empty or not

int isEmpty() {

    return top == -1;

}

// It is used to Check if the stack is full or not

int isFull() {

    return top == MAX - 1;

}

// Push operation (insert the data)

void push(int s_data) {

    if (!isFull()) {

        stack[++top] = s_data;

        printf("%d pushed to the stack successfully\n", s_data);

    } else {

        printf("Stack is overflow!\n");

    }

}

// Pop operation(Delete the data)

int pop() {

    if (!isEmpty()) {

        return stack[top--];

    } else {

        printf("Stack is underflow!\n");

        return -1;

    }

}

// Peek operation(To view the top element)

int peek() {

    if (!isEmpty()) {

        return stack[top];

    } else {

        printf("The Stack is empty!\n");

        return -1;

    }

}

int main() {

    int a[10],i,n;

    printf("How many numbers do you want to insert");

    scanf("%d",&n);

    printf("Enter the elements to insert one by one");

    for(i=0;i<n;i++)

    {

        scanf("%d",&a[i]);

        push(a[i]);

    }

    printf("The Top element is: %d\n", peek());

    printf("Popped: %d\n", pop());

    printf("Top element after pop: %d\n", peek());

    return 0;

}

Output:

How many numbers do you want to insert3

Enter the elements to insert one by one34 45 56

34 pushed to the stack successfully

45 pushed to the stack successfully

56 pushed to the stack successfully

The Top element is: 56

Popped: 56

Top element after pop: 45

Yes. The stack implementation is finished successfully. Hope, you understood this. Keep coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Symmetric Encryption in java

Java NIO examples to illustrate channels and buffers.