Follow these steps to implement a stack using a linked list:
- A structure is defined called node. In this structure, besides a data member for storing content for the stack, a pointer is also defined that points to the next node.
- The top pointer is initialized to NULL to indicate that the stack is currently empty.
- A menu is displayed and the user is asked whether they want to push or pop from the stack. The user can enter 1 to indicate that they want to push a value to the stack or enter 2 to indicate that they want to pop a value from the stack. If the user enters 1, go to step 4. If they enter 2, go to step 9. If they enter 3, it means they want to quit the program, so go to step 13.
- Allocate memory for the new node.
- Ask the user for the value to be pushed and assign that value to the data member of the node.
- Invoke the push function where the next pointer of the new node is set to point at top.
- The top pointer is set to point at the new node.
- Go to step 3 to display the menu.
- Check whether the top pointer is NULL. If yes, then display the message Stack is empty and go to step 3 to display the menu. If top is not NULL, go to the next step.
- A temporary pointer, temp, is set to point at the node where top is pointing.
- The top pointer is set to point to where its next pointer is pointing.
- Return the node that's being pointed at by temp as the popped node and display the data member of the popped node.
- Exit the program.
The program for implementing a stack using a linked list is as follows:
//stacklinkedlist.c
#include<stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
void push(struct node * NewNode, struct node ** Top);
struct node * pop(struct node ** Top);
int main() {
struct node * newNode, * top, * recNode;
int n = 0;
top = NULL;
while (n != 3) {
printf("\n1. Pushing an element into the stack\n");
printf("2. Popping out an element from the stack\n");
printf("3. Quit\n");
printf("Enter your choice 1/2/3:");
scanf("%d", & n);
switch (n) {
case 1:
newNode = (struct node * ) malloc(sizeof(struct node));
printf("Enter the value to push: ");
scanf("%d", & newNode - > data);
push(newNode, & top);
printf("Value %d is pushed to stack\n", newNode - > data);
break;
case 2:
recNode = pop( & top);
if (recNode == NULL) printf("Stack is empty\n");
else
printf("The value popped is %d\n", recNode - > data);
break;
}
}
return 0;
}
void push(struct node * NewNode, struct node ** Top) {
NewNode - > next = * Top;
* Top = NewNode;
}
struct node * pop(struct node ** Top) {
struct node * temp;
if ( * Top == NULL) return (NULL);
else {
temp = * Top;
( * Top) = ( * Top) - > next;
return (temp);
}
}
Now, let's go behind the scenes so that we can understand the code.