You are on page 1of 28
54 Queue sae linear list of elements in which deletions can take place only at one end, called te/ront, and insertions can take place only at the other end,.called the rear. Queues are slocalled First-In-First Out (FIFO) list, since the first element in a queue ueue will be the first tenent out of the queues. In other words, the order in which elements entered into a queue Ste order in which they leave. For example, at the railway reservation counter, people ‘tad in a queue to get the reservation. (@)D, £, and then F inserted Figure 5.5 A queue Figure ()ilsatesan empty queve whee the ronsinitaized oO and rears to-I. After insertion of A, B and C front is 0 and rear is 2. This is illustrated in Figure. - Figure 5.5 (c) shows the situation after deletion of A. Then D, E, and F are inserted ™** is shown inthe Figure 5.5 (4). A: 1 Operations on a Queue ) Create(q) Creates g as an empty queue. | Insert(q, i iit) Delete(q) 8) IsEmpty(q) ¥) IsFull(g) ‘Adds an element ito the rear of a queue. Removes the front element from the queve- Return true if gis empty otherwise returns false Retums true ifq is full otherwise returns false -eomalan st Gams Stacks & Queues # 5.41 a ce may be represented in memory in eT) Array representation i Linked list representation as array Representation of Queue s Wo ways: jement a queue we need an one-dimensional ay ‘with variables front which point tothe beginningot 1 end ofthe queue. Suppose thatthe elements of q can store maximum of 100 such elements, The fll define MAXQ 100 typedet struct 'Y which holds the data item and the queue and a rear which points lueue are of integer type, and the wing are the necessary declarations: pie infront, rear, intitems[MAXay, yueues queued; Intiscase,q isa variable of type queue. During the initialization of queue, frontiis set 0.0 wi ear insetto-1_ Onveach addition of a queue the variable rear is inerenened byl. On cterhand, in each delete operation the vari ble faukis incremented by 1. ostine to create an empty queue ° Set Oto front and -1 to rear of queue q when itis newly created */ voidCreate(queue “q) { 4>fron 4>ear = 1 Putine to check for an ‘empty queue Return true ifqisempty */ (semetqueue *a) (qerear reat return; else retund, y Routine to oid Insert(queue “4 *) insert an item into a queue ie(sFula)) pent ‘Overfiow), return, } > reartt: 4 itemajatearl = y Routine to remove an item from @ queue intDelete(qveue a) { int, if(sempty(q) print (UNDERFLOW?); ext (0); ) ese { = q> iems{q>tont > front ++; retumn x, ) } The queue is empty whenever is ver q.rear < q.front. The number a time is equal to the value of rear oa z Phe numberof lament eat .qude ine MAXQ 100 typedef struct atrontrear intitems[MAXQ); javeue itisEmpty(queve *) intlsFull(queue *); void Insert( queue *, nt); intDelete(queue *) void Display(queue *); void main() { quear=-1; while (ch I= { Printf(\n 1 - INSERT); Printf(“\n 2 - DELETE"); Printf(“\n 3 - DISPLAY"); print"\n 4 - QUIT); rintf(“\n\nEnter your choice: ) flush stain), ch= getchar(); ‘switeh(ch) case 't printf(“inenter the element tobe ins scant(%éd", 8%); Insen(&q,x); break; case ‘2: erted Dara Structures USINE. c jete(&4): on : jelement is %d\ xfcinDeleted 3K case pisplay(84): break; case ‘4 break: default printf"\nwrong choice Try again’); } } int sEmpty(queue “@) { itfq2reartont) return 1; alse return; } intlsFul(queue*q) ( itg>rear==MAXO-4) return 1; else return 0; } Void Insert(queue *g, intx) (sFul(q)) { printf"\nqueue ful return; 5 } q>reart+; q>items|a->rear] = x; ipetete(queue “a) int ilsémotva)) print"\nqueue empty"; exit 0); Ms qritemsiq->front}; qofront+; return x, } void Display(queue “q) { inti: if (isEmpty(q)) { print("\nqueue emptyin’); retum; } printf("WnElements in the queue are \n"); for (i=q->frontii<=q->reari++) printf"%din",q->itemsf); 4-INSERT 2-DELETE 5-DISPLAY 4-QUIT Enter your choice: 1 “nfer the element to be inserted : 11 1-INSERT 2-DELETE 3-DISPLay QUIT Ser your choice: 4 Stacks & Queues % 5,45 5.46 # Data Structures USN c ted: 33 center the element to be ins 4-INSERT 2-DELETE 3- DISPLAY 4-QUIT Enter your choice: + ther ne element tobe inserted : 22 4-INSERT 2-DELETE 3- DISPLAY 4-QuiT Enter your choice: 3 ements in the queue ar 1" 3 2 1-INSERT 2-DELETE 3-DISPLAY 4-QuIT Enter your choice: 2 Deleted elementis 11 4 -INSERT 2-DELETE 3- DISPLAY 4-QUIT Enter your choice: 3 Elements in the queue are 33 2 4-INSERT 2-DELETE 3-DISPLAY 4-QuIT Contd Vn yr choice: 3 events nthe queue are 2 4 INSERT DELETE S-0SPLAY ‘ou fteyour choice: 2 led element is 22 ascreuaras™ seats represented a lenithe rear pointer reaches st the end if able at the Font. One way To remorse scion panier tron is available at te Font. One way To enove ne Der aray. Physically a circular array is the same as ordi raat bees nary array, say, afm], but logically Spqstat 0] comes after a[n-1] or after afn-1), [0] appears Figure 5.7 shows logical psa! representations for a circular array creel (@)Circular queue (physical) (b) Circular queue (logical) Figure 5.7 Logical and physical view of a circular queue Fre 5.8 shows a cireular queue with 8 elements. Here we need two variables front and Seep track of the elements to be deleted and inserted and therefore it maintains the “characteristics of the queue. The following assumptions are made for circular: queue. aaa 8] a as) 2) a] “1 Figure 5.8 Circular queue with 8 elements 5.50 # Data Structures Using C 1) front will always be pointing to the first element, front ==1 lindas > “queue is empty ji) Each mea new element is inserted into the queue the rari ineremenedy rear = rear + = &, ii) Each time an element is déleted from the queue the value of fron is incene, 1. ke, front = front +1 “ell 3) fot = reg then queneeotains enyons semen! 529 foW = eo 5.4.6 Array Representation of Circular Queue ‘To implementa circular queue we need an one-dimensional array which holds the das and other two variables front which point to the beginning of the queue and a rear ia points to the end ofthe queue. Suppose that the elements of queue are of integer yp ay the queue can store maximum of 100 such elements, The following are the neces declarations: : ‘# define MAXQ 100 typedef struct { int front, rear; | inttems[MAXQ];, Jaueve; Routine to create an empty queue IP Set -1 to front and ~1 to rear of queue q when itis newly created */ void Create(queue “q) Routine to check for an empty queue /* Return true ifq is empty */ int IsEmpty(queve *a) to check fora full quoug Stacks & 0, ue ae cues # 5.51 r intisFull(queue *q) i(q->front return 4; ese return 0; (q>rear+1) % Maxa) } Insertion ‘omsider the circular queue shown in Figure 5.8, the insertion in this q ill ir ueue will be same as vihlinear queue, we only have to keep track of fo at ny : mnt and rear with civalar queue is shown in the Figure 5.9. When an i sicqune elon ture: an item is inserted into the queue we have rear = (rear + 1) % n; rear] = item; Figure 5.9 (b) shows insertion of an element into the queue. Figue 5.9 (c) shows queue is full, so no more insertion is possible. This can be implemented 'y the condition front == (rear +1) %n. ‘0b lee (b) item ; rear=rear +! and q{reatl item sertion int a circular’ queue Figure 5.9 Ins 5.52 & Data Structures Using C Routine to insert an item into 2 queue void Insert{queve “a. int) if(sFulla)) printinqueve full”): return: qorear=(q>reattt) %MAXQ: qoitemsiq>rear]= x: Del Whenever an element is deleted fom the queues the vale of fron isinoreasedh ix Font rom = 1) Soe fron == then queue isempy. Figure 5.10 shows thedelein ‘of elements from a circular queue. qe (a) before deletion front = 0, rear=3 (b) after deletion front = ew Figure $.10 Deletion from a circular queue Routine to remove an item from a queue int Delete(queue “a) { intx, if(lsEmpty(q)) Stacks & Queues % 5.53 { rintfenqueue empty’): exit (0); 2 geitemsta->tront it(q->front ->rear) q>tron q>rear= ) alse qetront= (@->front+1) % MAxa; return x; } 5.6_Implementation of circular queue using array jpa 6_plementaton of erulr guste wing aay ——————— Anclude tHefine MAXQ 100 typedef struct { intfront,rear, intitems[MAXQ]; Inveue; 'ntIsEmpty(queue *); in lsFull(queue *): \eid Insert(queue *, int) ‘ntDelete(queue : ‘6idDisplay(queue *); mano Queue g: Printf("\n 1 - INSERT"); 5,54 Deita Structures Using C ELETE’) printf printf"\n 3- DISPLAY’): print(\n 4 - QUIT’) printf¢\ninnter your choice: fflushi(stdin); = getchar(); switeh(ch) 2 case‘ printf(inenter the element o be inserted : ) scanf("%6d", 8%); Insert(8q.x): break; case 2: x= Delete(&q); printi("wnDeleted element is %din" x), break; case ‘3! Display(&q); break; case ‘4’ break; default printi(\mwrong choice | Try again’), d int smpty(queue *q) intIsFull(queue “q) { if{q->fror return 1; (q->rear+1) % MAXQ) else retum 0; ) void insert(queue "a, int x) if(isFull(q)) { Printf"\nqueue fun: retum; } it(q->tron ( g>tront = q>rear=0; } else a> rear= (q->rear+1) % MAXQ; q-ritems[q->rear } intDelete(queue *q) { int x: ‘f(IsEmpty(q)) { Print("inqueue empty’) exit (0); X= q>items(q->front} 'f(q->front == q->rear) { else ->front = (q->front+1) % MAXQ: return x; “®dDisplay(queue “q) ® Data Structures Using C { inti if(ismptyia)) { printf"inqueue empty"); return; } " pring Inelementsinthe queue te if(q->tront <= q->rear) pritf'%eain’ qitems{); for (i=0;i<=q->reari+*) printf"%ain" q>itemsf): } Output 1-INSERT 2-DELETE 3- DISPLAY 4-QUIT Enter your choice: 1 enter the element to be inserted : 33, 4-INSERT 2-DELETE 3- DISPLAY 4-QUIT Enter your choice: 1 enter the element to be inserted : 22, 4-INSERT 2-DELETE 3-DISPLAY 4-QuiT Enter your choice: 3 Elements in the queue are 3 Contd 2 — it ren 57 -INSERT fpevere SpisPLay 4-ouT ur choice: 1 Ene Mo olement 0 be inserted: 6g INSERT J. DELETE 5-DISPLAY 4-quT enter your choice: 3 ements in the queue are 3 2 6 4-INSERT 2-DELETE 5-DISPLAY 4-QuT Enter your choice: 2 Deleted element is 33, 1-INSERT 2-DELETE 3-DISPLAY 4.0UT Enter your choice: 3 Ekeents inthe queue are 8 {INSERT 2-DELETE ‘ 3-DISPLay our Ener your choice: 1 fete the elem ingen gementto be inserted: 44 2-DRL ETE Sy he samt & Data Structures Using C “4-QUIT : Enter your choice: Elements in the queue 21 2 6 44 4-INSERT 2-DELETE 3-DISPLAY 4-QUIT Enter your choice: 2 Deleted element is 22 4-INSERT 2-DELETE 3-DISPLAY 4-QUIT Enter your choice: 3 Elements in the queue are 6 uw 4-INSERT 2-DELETE 3=DISPLAY 4-QUT Enter your choice: 4 54.7 Linked ‘One major drawback of representing a queue by using array is that a fixed amount "2 remains allocated even when the structure is actually using a small amount or poss#)™ storage at all. Further, no more than that fixed amount of storage may be allt cc | representation of a queue introducing the possiblity of overflow. Figure 5.11 shows linked representation Here, each nodeis divided into two field. « info which holds the data clement ‘next which holds the address ofthe suecesor node Apart from that we need two more variables | «# front which holds the address ofthe frst node «# rear which holds the address ofthe last nade | Stacks & Queues # 5.59 rear FSS as Figure 5.11 Linked fi ist representation of queue ens sémpt(@) and Delete) are completely an get of stack, However, a special at aoe In that case, rear must al rust be NULL. tention is required when the lst elementis removed '$0 set to NULL, since in an empty queue both front ira sxdvantage of representing a stack or Meena coresponding lementinanaray, since igang ane piece a information is needed in the array implementation ean declare a queue as follows: strode { intinto; struct node “next; b ‘pate struct node “apt; pede struct { apt front rear, eveue; "tino create an empty queue "Set NULL to front and NULL to rear of queue q when itis newly created “7 widCreatequeue q) { 4-front= NULL; a= NULL; tho check or an empty queue "eu te it gis empty */ {rv aueve q 5.60 # Data Structures using C if(qetront == NULL) return 1: else return 0: t Routine to insertan item Into 2 queue void Insert(queue ant®) { ‘pir temp: tenp=(aptimalloc(sizeosouct node) if temp == NULL) printf(’ nut of memory space’); exit(O); ) temp>info=%; temp->next= NULL; if(q>rear==NULL) g-front= temp; ese (q>rear)>ned= tem; qerear= temp; } Routine to delete an item from a queue intDelete(queve a) { apirtemp; int, ‘f(sempty(a)) print('inqueue empty’); exi(0); i : temp =q->front, x= temp-info, q-tront ifq>tront q>rear= NULL; free(temp); return x 7 implementation of q Stacks & Oy 2 “sing linked fist —<—— E st amano 3 t info; get struct node “gptr; pede act © gtr trontrear, yeveve iasempty(queve): vod nsert(queve, int); intDelete(queue); vod Display(queue); voidmain() " qevegrNULL int x; char ch = “1° g>front= NULL; tear = NULL; otrser() while (ch { Printf(\n 1 - INSERT"); Print‘\n 2 - DELETE”); Printi(‘\n 3 - DISPLAY"); Printf(“\n 4 - QUIT"); Printf("\n\nEnter your choice:"); fflushstainy; ch= getchar(): swcnien) ) case "1" : Printf(“\nEnter the element to be inserted"); Scanf("%d",&x); wpe ‘break cose?! in"): 2 peiete(d: x ose retement i % break: case" Display break: case 4 break: default printfa cP ice Try aga": } i intisempty(queve @) NULL) , void Insert(queve g.intx) { gptr temp; temp=(qptimalloc(szeotstruct node) if (temp == NULL) Z printf("\nout of mem ") exit); oe if(q>rear==NULL) else oe (q>rear}>next= Ae t= temp; —— Stacks & Queues # 5.63 if C prteme: apt aK wuseme4(@) print"inqueve empty’); ext(0; 1 vad Oislayiqueve q) ( apt tr pir=q>rear print-inThe elements inthe queue are’) if(otr== NULL) é printf(\nqueue emplyinin’); retum; ) : fe(pttqfront;pr!=NULL; plrpt->nest) print’ pt->info), Output ‘INSERT 2-DELETE S-OispLay “QUT Sieryourchoice't Contd 5,64 # Dara Structures USING c Enter the element 0 Be inserted 11 Enter your choice: t Ente element io be inserted 39 1 INSERT 2-DELETE 3- DISPLAY 4-QUT Enter your choice:t Enter the element tobe inserted:22 1 -INSERT 2-DELETE 3- DISPLAY 4-QUIT Enter your choice’3 The elements inthe queue are 1 3 2 4-INSERT 2-DELETE 3-DISPLAY 4-QUIT Enter your choice:2 The deleted ielementis 11 41-INSERT 2-DELETE 3-DISPLAY 4-QUIT Enter your choice:3 ‘The elements in the queue are 3B 2 Contd ur choice:2 eared elementis 33 yout choice: Fre elements inthe queue are 2 4 INSERT 7-DELETE 4-DISPLAY 4-uT snteryour choice:2 ‘Thadeleted lelementis 22 1-INSERT 2-DELETE 3-DISPLAY 4-0UT Enter your choice:3 Theelements in the queue are ‘queue empty. 1-INSERT 2-DELETE 3-DISPLAY 4QuT . Eater your choice:4 ieiyor chet oe 5.66 * Data Structures Using C 5.5 Deque ‘A deque is linear list in which elements.can be added or removed a ether end but notin he aradale, The term deque is a contraction ofthe name double-ended queue. middle. a jeque. These two vari deletions only at one ations are due to the restrictions pyy, ‘These are two variations of a d perform ether the insertions or end. They are r j) Input-restricted deque and ii) Output restricted deque restrited deques are intermediate between a deque and aque, ted deque isa deque which allows insertions at only one endot oth ends ofthe list; and an output-restricted deque isa deqy “Jof te list ut allows insertions at both ends ofthe i, Input restricted and output Specifically, an input rest thelist but allows deletions at which allows deletion at only one en front rear ton = ae 18 2s | ~ + | 75 | 95 | 85 Insertion —>| Figure 5 .12 Double ended queue ‘Since both insertion and deletion are performed from either end, it is necessary to design algorithm to perform the following four operations. a) Insertion of an element at the rear end of the queue. b) Deletion of an element from the front end of the queue. c) Insertion of an element at the front end of the queue. d) Deletion of an element from the rear end of the queue. We leave the development of algorithm and program to the reader. 46 Prion ity Queues Stacks & Queues % 5.73 ty queue is a collection of elemenys _ su whiel AM gpd such thatthe order in which ce eh at h cleme 3 MS are d Dt has been ass flowing ules : eld and processed comesfoes the }) Anelement of high "ot i processed ep fo G Two elements with the sam, - le priorit they were add tothe queye = POSE Acorn tothe orem wich nexample of priority queue in com jose of higher priority is exec ¥ element of lower priority Puter science occur Sin ti i uted before any pro intimesharing system in which the ie e88 of lower priority, ‘here are two types of priority queues; AF, ascending priority queue 7p descending priority queue Anascending priority queviei a collection of items into whichitems canbe inserted arbitarly and from which only the smallest item can be removed. A descending priority queue is Sinilar but allows deletion of only the largestitem. We leave the development of algorithm and program to the reader. 57 Application of Queue As Queue is a FIFO structure, it is an appropriate data structure for used in numerous ‘pplcations of computer science. One important application of queue simulation. Queues i i i Itis used to implement bs i Jus aspects of operating systems. ‘mainly used to implement various aspect as et ‘iffeent CPU scheduling algorithms. Multiprogramming envi eae ‘control various programs. Some of the applications of queue are * Simulation of traffic control system © CPUscheduling in maltiprogrammingand Multilevel queue scheduling # Multilevel feedback queve seheduling «¢ Round Robin schedulingalgorihm time sharing environment

You might also like