-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathass2_4q.c
111 lines (111 loc) · 2.53 KB
/
ass2_4q.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include<stdio.h>
#include<stdlib.h>
struct N{
int data;
struct N *next;
};
int no=0;// to count the total number of the nodes present into the linked list.
struct N *front=NULL,*rear=NULL;
void display(); //done
struct N* create(); //done
void enqueue();
void dequeue();
int count() //done
{
int n;
struct N *temp;
if(!front)
return 0;
temp=front;
for(n=1;temp->next;n++)
temp=temp->next;
return n;
}
void main()
{
int ch,pos;
char c;
do
{
printf("Press 1 to insert an iten in the queue.\nPress 2 to delete an item from the queue.\nPress 4 to count the number of the items present into the queue.\nPress 3 to display all the items in the queue.\nEnter your choice: ");
scanf("%d",&ch);
switch (ch)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
printf("The total nodes present into the linked list are: %d\n",count());
break;
default:
printf("\nWrong Input!!");
break;
}
printf("Do you wanna continue?[y/n] ");
scanf(" %c",&c);
} while (c!='n');
}
struct N* create()
{
struct N *temp;
int x;
temp=(struct N*)malloc(sizeof(struct N));
printf("Enter the data present into the node: ");
scanf("%d",&x); // this gives you the ability to take user input and connect it with the node.
temp->data=x;
temp->next=NULL;
return temp;
}
void display()
{
struct N *temp;
if(!front)
printf("The Queue is empty. Nothing is to show.\n");
else
{
printf("The items into the Queue are: \n");
temp=front;
while (temp->next)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("%d \n",temp->data);
}
}
void enqueue()
{
if(!front) //it means front is not been initialised yet. Initialise it first.
rear=front=create();
else
{
rear->next=create();
rear=rear->next; // rear is always pointing to the last node.
}
no++;
}
void dequeue()
{
struct N *t;
if(!front)
printf("The Queue is empty.\n Nothing is to dequeue.\n");
else if (front==rear) // there's only one single node is present into
{
free(rear); // resetting the linked list.
rear=front=NULL;
no=0;
}
else
{
t=front;
front=front->next;
free(t);
no--;
}
}