data structure stack

Stack is a linear data structure that follows a Last In First Out(LIFO) or First In Last Out(FILO) order in which the operations are performed. In stack insertion and deletion operation occurs at the same end and a TOP is maintained that indicates the topmost element of the stack.
The real-life stack example can be a pile of plates, you place the new plate on the top and remove the plate from the top itself.
The stack data structure is used in Undo functionality of an editor, storing function calls in a recursive program.

Stack Operations: 
1) push() : Inserts an element at the top of the stack
2) pop() : Removes the topmost element from stack
3) top() : Returns the topmost element
4) printList() : Print stack elements


struct node {
          int data;
          struct node *next;
struct node *TOP;
/*c program to implement stack using array*/
#include <stdio.h>
#include <stdlib.h>
#define MAX 256

int stack[MAX];
int top = -1;
int pop();
void push(int);

int main()
        int i = 0, n, data;
        printf("Enter the number of elements:\t");
        scanf("%d", &n);
        printf("Enter elements:\n");
        for (i = 0; i < n; i++)
                scanf("%d", &data);

        printf("\nTop of stack is %d", stack[top]);
        printf("\nPopped element is %d", pop());

        printf("\nTop of stack is %d", stack[top]);

        return 0;

void push(int item)
        if (top == (MAX - 1))
                printf("\nStack Overflow\n");
        stack[++top] = item;

int pop()
        if (top == -1)
                printf("\nStack Underflow\n");
        return stack[top--];

$ gcc stack.c
$ ./a.out
Enter the number of elements: 4
Enter elements:
Top of stack is 4
Popped element is 4
Top of stack is 3

NOTE: The time complexity of push(), pop(), top() is O(1) as we perform all the operations on the top node.

also see

C Programming language
Go Programming language
Linked List Array
Simplification Queue
DBMS Reasoning
Aptitude HTML
Previous articleGetting started with C
Next articleMerge and Sort two Linked list in C


Please enter your comment!
Please enter your name here