Pages

Thursday, August 11, 2016

C Program for Stack using linked list

Program:-

//C Program for Stack using linked list

#include<stdio.h>
#include<stdlib.h>
struct link
{
int info;
struct link * next;
};
struct link * start=NULL;

void insert();
void show();
void del();

void main()
{
int ch,temp;
do
{
printf("\n\t Main menu");
printf("\n 1:insert");
printf("\n 2:delete");
printf("\n 3:Show");
printf("\n 4:Exit");
printf("\n Enter Your Choice ");
scanf("%d",&ch);
switch(ch)
{
case 1: insert(); break;
case 2: del(); break;
case 3: show(); break;
case 4: temp=1; break;
default: printf("\n wrong choice");
}
}while(ch!=4 && temp!=1);
}

void insert()
{
struct link * temp,* move;
int num;
temp=(struct link *)malloc(sizeof(struct link));
printf("Enter the number\n");
scanf("%d",&num);
temp->info=num;
temp->next=NULL;
if(start==NULL)
start=temp;
else
{
move=start;
while(move->next!=NULL)
{
move=move->next;
}
move->next=temp;
}
}

void del()
{
struct link * back,* move;
int item;
if(start==NULL)
printf("link list is empty");
else
{
move=start;
if(move->next==NULL)
{
item=move->info;
start=NULL;
}
else
{
while(move->next!=NULL)
{
back=move;
move=move->next;
}
item=move->info;
back->next=NULL;
}
printf("item deleted=%d",item);
}
}

void show()
{
struct link * temp,* move;
if(start==NULL)
printf("list is empty");
else
{
move=start;
printf("Elements are ");
while(move->next!=NULL)
{
printf("%d\n",move->info);
move=move->next;
}
printf("%d\n",move->info);
}

}


Output:-



Main menu
 1:insert
 2:delete
 3:Show
 4:Exit
 Enter Your Choice 1
Enter the number
10

Main menu
 1:insert
 2:delete
 3:Show
 4:Exit
 Enter Your Choice 1
Enter the number
20

Main menu
 1:insert
 2:delete
 3:Show
 4:Exit
 Enter Your Choice 1
Enter the number
30

Main menu
 1:insert
 2:delete
 3:Show
 4:Exit
 Enter Your Choice 3
Elements are 10
20
30

Main menu
 1:insert
 2:delete
 3:Show
 4:Exit
 Enter Your Choice 2
item deleted=30
Main menu
 1:insert
 2:delete
 3:Show
 4:Exit
 Enter Your Choice 3
Elements are 10
20

Main menu
 1:insert
 2:delete
 3:Show
 4:Exit
 Enter Your Choice 4


No comments:

Post a Comment