Data Structures: Stack Code

📢 This article was translated by gemini-2.5-flash

Sequential Stack (Array Implementation)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>

// Push element 'elem' onto stack. 'a' is the array, 'top' is current stack top index.
int push(int* a,int top,int elem)
{
    a[++top]=elem;

    return top;
}

// Pop element from stack
int pop(int * a,int top)
{
    if (top==-1) 
    {
        printf("Stack is empty\n");
        return -1;
    }
    printf("Popped element: %d\n",a[top]);
    top--;

    return top;
}

int main(void) 
{
    int a[100];
    int top=-1;

    top = push(a, top, 1);
    top = push(a, top, 2);
    top = push(a, top, 3);
    top = push(a, top, 4);
    top = pop(a, top);
    top = pop(a, top);
    top = pop(a, top);
    top = pop(a, top);
    top = pop(a, top);
    
    return 0;
}

Output:

Popped element: 4
Popped element: 3
Popped element: 2
Popped element: 1
Stack is empty

Linked Stack

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>

typedef struct lineStack{
    int data;
    struct lineStack * next;
}lineStack;

// 'stack' is the current linked stack, 'a' is the element to push
lineStack* push(lineStack * stack,int a)
{
    // Create a new node to store the element
    lineStack * line=(lineStack*)malloc(sizeof(lineStack));
    line->data=a;
    // Link new node to the current head
    line->next=stack;
    // Update head pointer
    stack=line;

    return stack;
}

// Function to pop top element from linked stack
lineStack * pop(lineStack * stack)
{
    if (stack) 
    {
        // Declare a new pointer to the top node
        lineStack * p=stack;
        // Update head pointer
        stack=stack->next;
        printf("Popped element: %d ",p->data);
        if (stack) 
        {
            printf("New top element: %d\n",stack->data);
        }
        else
        {
            printf("Stack is empty\n");
        }
        free(p);
    }
    else
    {
        printf("No elements in stack\n");

        return stack;
    }

    return stack;
}

int main(void) 
{
    lineStack * stack=NULL;

    stack=push(stack, 1);
    stack=push(stack, 2);
    stack=push(stack, 3);
    stack=push(stack, 4);
    stack=pop(stack);
    stack=pop(stack);
    stack=pop(stack);
    stack=pop(stack);
    stack=pop(stack);
    
    return 0;
}

Output:

Popped element: 4 New top element: 3
Popped element: 3 New top element: 2
Popped element: 2 New top element: 1
Popped element: 1 Stack is empty
No elements in stack