Table of Contents
Implementing a Stack Using Linked List: Step-by-Step Guide
The first implementation of a stack uses a singly linked list. We perform a push by inserting at the front of the list. We perform a pop by deleting the element at the front of the list. A top operation merely examines the element at the front of the list, returning its value. Sometimes the pop and top operations are combined into one. We could use calls to the linked list routines of the previous section, but we will rewrite the stack routines from scratch for the sake of clarity.
/* STACK IMPLEMENTATION USING LINKED LIST */
# include
# include
struct link
{
int info;
struct link *next;
} *start;
void display(struct link *);
struct link *push(struct link *);
struct link *pop(struct link *);
int main_menu();
void display(struct link *rec)
{
while(rec != NULL)
{
printf(" %d ",rec->info);
rec = rec->next;
}
}
struct link * push(struct link *rec)
{
struct link *new_rec;
printf("\n Input the new value for next location of the stack:");
new_rec = (struct link *)malloc(sizeof(struct link));
scanf("%d", &new_rec->info);
new_rec->next = rec;
rec = new_rec;
return(rec);
}
struct link * pop(struct link *rec)
{
struct link *temp;
if(rec == NULL)
{
printf("\n Stack is empty");
}
else
{
temp = rec->next;
free(rec);
rec = temp;
printf("\n After pop operation the stack is as follows:\n");
display(rec);
if(rec == NULL)
printf("\n Stack is empty");
}
return(rec);
}
int main_menu ()
{
int choice;
do
{
printf("\n 1
Output
1