This is a C program that implements the stack operations using a linked list. The program includes stack operations like push operation, pop operation, Display and Quit option.
struct node { int data; struct node *link; }*top=NULL;
To insert an element to the stack. In a stack, a new element is always added from the top of the stack.
Given below is the function used in the code for push operation.
We declare a pointer to node i.e. newnode and allocate memory from heap using malloc function. We take input for the data part of newnode from the user. We update the link of newnode to top and make newnode the new top.
void push(int x) { struct node *newnode; newnode=(struct node *)malloc(sizeof(struct node)); newnode->data=x;
newnode->link=top; top=newnode; }
To delete an element from the stack. In a stack, an element is always deleted from the top of the stack.
Given below is the function used in the code for the pop operation.
First, we check if the stack is empty. If not, we take a pointer temp equal to the top. We change the top to the link of top and free temp.
void pop() { struct node *temp; temp=top; if(top==NULL) { printf("Stack underflow\n"); } else { top=top->link; free(temp); } }
To display the elements in the stack.
Given below is the function to display the elements of the stack.
void display() { if(top==NULL) { printf("Stack Empty\n"); } else { for(struct node *temp=top;temp!=NULL;temp=temp->link) { printf("%d ",temp->data); } } }
Submitted by Srishti Dhaval Patkar (srishtipatkar15)
Download packets of source code on Coders Packet
Comments