Stack implementation in C using array
Stack is a linear data structure which follows the principle of Last In First Out. It follows memory management and flexibility.
Stack can be implemented by two ways
- Using Arrays
- Using Linked list.
Let us implement the stack in both of the ways.
1.Using Array
If you
want the stack to be implemented as static unit, this method suits you. It has
same size of data that can be defined in compile time.
Code snippet:
#include <stdio.h>
#define SIZE 100
int a_stack[SIZE];
int a_top = -1;
void a_push(int s_value) {
if (a_top >=
SIZE - 1)
printf("The Stack is Overflow\n");
else {
a_stack[++a_top] = s_value;
printf("Pushed %d onto the stack\n", s_value);
}
}
int a_pop() {
if (a_top < 0)
{
printf("The Stack is Underflow\n");
return -1;
} else {
int s_value =
a_stack[a_top--];
printf("Popped %d from the stack\n", s_value);
return
s_value;
}
}
int a_peek() {
if (a_top < 0)
{
printf("Stack is empty\n");
return -1;
} else {
printf("The top element is %d\n", a_stack[a_top]);
return
a_stack[a_top];
}
}
void display() {
if (a_top < 0)
{
printf("The Stack is empty\n");
} else {
printf("The Stack contents: ");
for (int i =
a_top; i >= 0; i--)
printf("%d -> ", a_stack[i]);
printf("NULL\n");
}
}
int main() {
a_push(11);
a_push(34);
a_push(99);
a_push(125);
a_push(250);
a_peek();
display();
a_pop();
a_peek();
display();
return 0;
}
Output:
Pushed 11 onto the stack
Pushed 34 onto the stack
Pushed 99 onto the stack
Pushed 125 onto the stack
Pushed 250 onto the stack
The top element is 250
The Stack contents: 250 -> 125 -> 99 -> 34 -> 11
-> NULL
Popped 250 from the stack
The top element is 125
The Stack contents: 125 -> 99 -> 34 -> 11 ->
NULL
Next, code snippet is for creating stack using linked list.
Comments
Post a Comment