Thursday, June 18, 2015

Stack Implementation in C

Today i gonna show you a simple example of stack implementation in C. The stack is a very common data structure used in programs.

"In computer science, a stack or LIFO (last in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the last element that was added."

Ok, but talk is cheap. Show me the code.

 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
#include <stdio.h>
#include <malloc.h>

#define MAX 50 // Maximum size of array

int index = 0; // Index of values

// Stack data structure
typedef struct{
    int value;
}Structure, *Pointer;

// Initializes the stack
void initialize(Pointer stack[]){
    for (int i = 0; i < MAX; ++i){
        stack[i] = NULL;
    }
}

// Push a value on the stack
void push(Pointer stack[], int value){
    Pointer temp = (Pointer) malloc( sizeof(Structure) ); // Allocates memory
    temp->value = value; // Puts the value on the structure
    stack[index] = temp; // Puts the new structure on the stack
    index++;
}

// Delete a value from the stack
void pop(Pointer stack[]){
    stack[index] = NULL;
    index--;
}

// Shows the stack
void show(Pointer stack[]){
    printf("STACK : ");
    for (int i = 0; i < index; ++i){
        printf("[%d]-", stack[i]->value);
    }
    printf("\n");
}

int main(){
    Pointer STACK[MAX];
 
    initialize(STACK);
 
    push(STACK, 15);
    push(STACK, 55);
    push(STACK, 80);
    push(STACK, 99);
    push(STACK, 43);

    show(STACK);
    pop(STACK);
    show(STACK);
    pop(STACK);
    show(STACK);
    pop(STACK);
    show(STACK);

    return 0;
}

If you have any questions or suggestions, please leave your comment.

No comments:

Post a Comment