This is a C program which implements queue using linklist.
Source Code:
- #include<stdio.h>
- #include<conio.h>
- #include<malloc.h>
- //A structure is created for the node in queue
- struct queu
- {
- int info;
- struct queu *next;//Next node address
- };
- typedef struct queu *NODE;
- //This function will push an element into the queue
- NODE push(NODE rear)
- {
- NODE NewNode;
- //New node is created to push the data
- NewNode=(NODE)malloc(sizeof(struct queu));
- printf ("\nEnter the no to be pushed = ");
- scanf ("%d",&NewNode->info);
- NewNode->next=NULL;
- //setting the rear pointer
- if (rear != NULL)
- rear->next=NewNode;
- rear=NewNode;
- return(rear);
- }
- //This function will pop the element from the queue
- NODE pop(NODE f,NODE r)
- {
- //The Queue is empty when the front pointer is NULL
- if(f==NULL)
- printf ("\nThe Queue is empty");
- else
- {
- printf ("\nThe poped element is = %d",f->info);
- if(f != r)
- f=f->next;
- else
- f=NULL;
- }
- return(f);
- }
- //Function to display the element of the queue
- void traverse(NODE fr,NODE re)
- {
- //The queue is empty when the front pointer is NULL
- if (fr==NULL)
- printf ("\nThe Queue is empty");
- else
- {
- printf ("\nThe element(s) is/are = ");
- while(fr != re)
- {
- printf("%d ",fr->info);
- fr=fr->next;
- };
- printf ("%d",fr->info);
- }
- }
- int main()
- {
- int choice;
- char option;
- //declaring the front and rear pointer
- NODE front, rear;
- //Initializing the front and rear pointer to NULL
- front = rear = NULL;
- do
- {
- //clrscr();
- printf ("1. Push\n");
- printf ("2. Pop\n");
- printf ("3. Traverse\n");
- printf ("\n\nEnter your choice = ");
- scanf ("%d",&choice);
- switch(choice)
- {
- case 1:
- //calling the push function
- rear = push(rear);
- if (front==NULL)
- {
- front=rear;
- }
- break;
- case 2:
- //calling the pop function by passing
- //front and rear pointers
- front = pop(front,rear);
- if (front == NULL)
- rear = NULL;
- break;
- case 3:
- traverse(front,rear);
- break;
- }
- printf ("\n\nPress (Y/y) to continue = ");
- fflush(stdin);
- scanf ("%c",&option);
- }while(option == 'Y' || option == 'y');
- }
Output:
1. Push
2. Pop
3. Traverse
Enter your choice = 1
Enter the no to be pushed = 14
Press (Y/y) to continue = Y
1. Push
2. Pop
3. Traverse
Enter your choice = 1
Enter the no to be pushed = 25
Press (Y/y) to continue = Y
1. Push
2. Pop
3. Traverse
Enter your choice = 1
Enter the no to be pushed = 36
Press (Y/y) to continue = Y
1. Push
2. Pop
3. Traverse
Enter your choice = 2
The poped element is = 14
Press (Y/y) to continue = Y
1. Push
2. Pop
3. Traverse
Enter your choice = 3
The element(s) is/are = 25 36
Press (Y/y) to continue = N
0 comments:
Post a Comment