Representation and Implementation of Stack
In C language, a stack can be implemented using an array or a linked list. Here is an example implementation of a stack using an array:
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
// Push operation
void push(int item) {
if (top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
} else {
top++;
stack[top] = item;
}
}
// Pop operation
int pop() {
int item;
if (top < 0) {
printf("Stack Underflow\n");
return -1;
} else {
item = stack[top];
top--;
return item;
}
}
// Display operation
void display() {
int i;
if (top < 0) {
printf("Stack is Empty\n");
} else {
printf("Stack elements are:\n");
for (i = top; i >= 0; i--)
printf("%d\n", stack[i]);
}
}
In this implementation, the push
operation adds an element to the top of the stack, the pop
operation removes the top element from the stack, and the display
operation displays all the elements of the stack.
Here is an example implementation of a stack using a linked list:
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
// Push operation
void push(int item) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = item;
newNode->next = top;
top = newNode;
}
// Pop operation
int pop() {
int item;
struct Node* temp;
if (top == NULL) {
printf("Stack Underflow\n");
return -1;
} else {
temp = top;
item = temp->data;
top = top->next;
free(temp);
return item;
}
}
// Display operation
void display() {
struct Node* temp;
if (top == NULL) {
printf("Stack is Empty\n");
} else {
temp = top;
printf("Stack elements are:\n");
while (temp != NULL) {
printf("%d\n", temp->data);
temp = temp->next;
}
}
}
In this implementation, the push
operation creates a new node with the given data and adds it to the top of the stack, the pop
operation removes the top node from the stack and returns its data, and the display
operation displays all the elements of the stack.