1. Implement a Stack using Linked List
#include
#include
struct Node
{
int Data;
struct Node *next;
}*top;
void popStack()
{
if(top!=NULL)
{
top = top->next;
}
else
printf("\nStack Empty");
}
void push(int value)
{
struct Node *temp;
temp=(struct Node *)malloc(sizeof(struct Node));
temp->Data=value;
if (top == NULL)
{
top=temp;
top->next=NULL;
}
else
{
temp->next=top;
top=temp;
}
}
void display()
{
struct Node *var=top;
if(var!=NULL)
{
printf("\nElements are as:\n");
while(var!=NULL)
{
printf("\t%d\n",var->Data);
var=var->next;
}
printf("\n");
}
else
printf("\nStack is Empty");
}
int main(int argc, char *argv[])
{
int i=0;
top=NULL;
printf(" \n1. Push to stack");
printf(" \n2. Pop from Stack");
printf(" \n3. Display data of Stack");
printf(" \n4. Exit\n");
while(1)
{
printf(" \nChoose Option: ");
scanf("%d",&i);
switch(i)
{
case 1:
{
int value;
printf("\nEnter a valueber to push into Stack: ");
scanf("%d",&value);
push(value);
display();
break;
}
case 2:
{
popStack();
display();
break;
}
case 3:
{
display();
break;
}
case 4:
{
struct Node *temp;
while(top!=NULL)
{
temp = top->next;
free(top);
top=temp;
}
exit(0);
}
default:
{
printf("\nwrong choice for operation");
}
}
}
}
2. Implement a Queue using Linked List
#include
void enq();
void deq();
void display();
main()
{
int n;
printf("\tMENU\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY\n4.EXIT\n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
enq();
break;
case 2:
deq();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Invalid choice\n");
break;
}
}
while(n!=4);
}
typedef struct node
{
int data;
struct node *link;
}n;
n *front=NULL;
n *rear=NULL;
void enq()
{
int item;
n *temp;
printf("Enter the item\n");
scanf("%d",&item);
temp=(n*)malloc(sizeof(n));
temp->data=item;
temp->link=NULL;
if(rear==NULL)
{
front=temp;
rear=temp;
}
else
{
rear->link=temp;
rear=temp;
}
}
void deq()
{
int item;
if(front==NULL)
printf("Queue is empty\n");
else
{
item=front->data;
printf("The element deleted = %d\n",item);
}
if(front==rear)
{
front=NULL;
rear=NULL;
}
else
front=front->link;
}
void display()
{
n *ptr;
if(front==NULL)
printf("Queue is empty\n");
else
{
ptr=front;
printf("The elements of the queue are :");
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->link;
}
}
}
0 comments:
Post a Comment