How to implement stack in C programming ?

In continuation of demonstrating simple implementation of data structures, as we shown in our last post “How to implement linked list in C programming ?”, in this post we will show how you can implement simple stack in C programming language. Stack is nothing but a one this kept on another, where we define how many maximum elements can be kept in one stack and what is the current size of the stack.

$ vim simple_stack.c
#include <stdio.h>
#include <stdlib.h>

struct stack {
        int top;
        int max_elements_in_stack;
        int *array;
};

void push(struct stack *s, int value) {
        s->top = ++s->top;
        s->array[s->top] = value;
}

int pop(struct stack *s) {
        int val = s->array[s->top];
        s->top = --s->top;
        return val;
}

struct stack *init_stack(int count) {
        struct stack *s = (struct stack *)malloc(sizeof(struct stack));
        s->top = -1;
        s->max_elements_in_stack = count;
        s->array = (int *) malloc(sizeof(int) * count);
}

int main(int argc, char **argv) {
        int max_elements_in_stack = 100;
        struct stack *st = init_stack(max_elements_in_stack);

        push(st, 10);
        push(st, 20);
        push(st, 30);
        push(st, 40);
        printf("popped value is %d\n", pop(st));
        printf("popped value is %d\n", pop(st));
        return 0;
}

The above program, implements simple stack which holds maximum 100 elements and we initialise this stack with “init_stack” and simple function “push” adds an element into stack and pop removes an element from stack [ here stack is just a simple array of integers]

Related :   How to solve : error: invalid operands to binary % (have ‘float’ and ‘double’)

We can compile the program as,

$ gcc -o simple_stack simple_stack.c
$ ./simple_stack 
popped value is 40
popped value is 30

lynxbee_ezoic

Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )

   


Leave a Comment

Android Android Applications Android Build system Android Commands Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded