Stack using Linked list in C
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
struct node
{
int data;
struct node*next;
};
struct node*head, *temp, *top, *newnode;
void push()
{
int choice=1;
while(choice==1)
{
newnode=(struct node*)malloc(sizeof(struct node));
newnode->next=0;
printf("enter the data: ");
scanf("%d",&newnode->data);
if(head==0)
{
head=newnode;
temp=newnode;
}
else
{
// we are pushing the elements in stack from head side;
//or we can say the top is at head;
newnode->next=head;
head=newnode;
}
printf("want to push another element to stack(0,1): ");
scanf("%d",&choice);
}
}
void pop()
{
int choice=1;
while(choice==1)
{
temp=head;
if(head==0)
{printf("\nSTACK UNDERFLOW\n");break;}
else
{
printf("deleted %d from stack\n",temp->data);
head=temp->next;
free(temp);
}
printf("want to pop another element to stack(0,1): ");
scanf("%d",&choice);
}
}
void display()
{
temp=head;
if(head==0)
printf("Stack empty\n");
else
{
printf("\nSTACK IS :\n");
while(temp!=0)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
}
int main()
{
head=0;
int choice=1,ch;
while(choice==1)
{
printf("enter 1. to Push element in stack\n");
printf("enter 2. to pop element in stack\n");
printf("enter 3. to display elements of stack\n");
scanf("%d",&ch);
if(ch==1)
{
push();
}
else if(ch==2)
{
pop();
}
else if(ch==3)
{
display();
}
else
printf("Invalid Choice");
printf("Do you want to continue (0,1): ");
scanf("%d",&choice);
}
}
Comments
Post a Comment