[C] Stack

1 minute read

The stack is literally a data structure in the form of stacking data one by one. The stack is also a data structure that is accessed and processed from the top, just as it is impossible to remove the book from the bottom when the books are stacked one after another in a box. This data structure is called a last-in-first-out structure because the last inserted data is deleted first. A stack is a data structure that stacks or returns data of the same structure and size in one direction, and stacks data from the bottom to the top. In general, an index called top is used, and the process of putting data is called push, and the process of pulling out data is called pop.


#include <stdio.h>
#define s_size 100

int stack[s_size];
int top = -1;

int empty_check(){
    if (top == -1 ) return 1;
    else return 0;
}

int full_check(){
    if (top== s_size - 1) return 1;
    else return 0;
}

void push(int x){
    if (full_check()) return;
    else stack[ ++top ]= x;
    return;
}

int pop(){
    if (empty_check()) return -1;
    else return stack[top--];       
}

int main(){
    push(1);
    printf("%d\n", stack[top]);

    push(2); 
    push(3);
    pop();
    printf("%d", stack[top]);

    return 0;
}
1
2

The simplest way to implement the stack is to implement it through an array of a certain size, and declare and use a stack array of a certain size. Since the index of the location where the first element is to be stored is 0, top is initialized to -1 for convenience of operation. Since the size of the array is declared in advance, it is necessary to check the condition of whether the size of the array is exceeded and whether the array is not empty. When inserting data in an array, a value is assigned to the position where the index of top is increased, and for deletion, a post-value operation is performed that decreases (moves) top by 1 after deleting the currently located element.

The stack code implemented in a simple form is as follows.

#include <stdio.h>

int stack[100];
int top = -1;

int main(){

    stack[++top]=1;
    printf("%d\n", stack[top]);

    stack[++top]=2; 
    stack[++top]=3;

    printf("%d", stack[--top]);

    return 0;
}
1
2