Docsity

QUEUES in c using data structures, Summaries of Computer science

Partial preview of the text

Download QUEUES in c using data structures and more Summaries Computer science in PDF only on Docsity!

a. UNIT- 4 ; wns | | e Queue is a linear data structure in which elements can be inserted from one end called rear and deleted from other end called front. © The deletion or insertion of elements can take place only at the front or rear end called | nt that gets added into the queue is dequeue and enqueue respectively. The first eleme he queue is referred to as First-In- re PAY the first one to get removed from the queue. Hence t First-Out list (FIFO). ¢ Operations performed on Queue: : front } d ona queue. They are There are two possible operations performe ng an element at the rear of the queue. v¥ enqueue: Allows inserti Vv dequeue: Allows removing an element from the front of the queue. I} [ REPRESENTATION OF QUEUEs: | ARRAYs: Queues can be easily . os . (tz [9 7 [18 | 14 | 36 | | represented using linear arrays. Every Fo 1 3 3 4 5p 6 3 5 9 queue has front and rear variables that Initial Quene point to the position from where deletions Enqueue(45) 7 [18] 4 [36 [45 | | | Liz [9 | = ne re a rr er and insertions can be done, respectively. Queue after insertion of a new element The array representation of a queue is DequeueQ shown | 3] 7 | 18114 [ 36 | 45 Drawback: The array must be declared to 0 Fl 2 3 4 5 6p 7 & 9 ] Queue after deletion of an element have some fixed size. If we allocate space TIRUMALAENGINEERING COLLEGE ee A, < . alf of ace will -He for 50 elements in the queue and it hardly uses 20-25 locations, then half of the space will Be wasted. LINKED LISTs: Ina linked queue, every element has two parts, one that stores the data and another that stores the address of the next element. The START pointer of the linked list is used as FRONT. Here, we will also use another pointer called REAR, which will store the address of the last element in the queue. All insertions will be done at the rear end and all the deletions will be done at the front end. ¢ IfFRONT = REAR = NULL, then it indicates that the queue is empty. 9] p74 7 3] 4447-12] 16 5|x Front Tntial Queue Rear DequeueQ 1] 47] 3 4 >} 27-—+>{6] 4 5] x Front Rear EnqueueQ) 1] 477 73 4) 427 +467 bf 5] 1 9[x Front Rear [ IMPLEMENTATION OF QUEUES: | Using Arrays: Algorithm for ENQUEUE operation 1. Check whether queue is FULL. (rearSIZE-1) 2. If it is FULL, then display an error message "Queue is FULL!!! Insertion is not possible!!!" and terminate the function. 3. If it isNOT FULL, then increment rear value by one (rear++) and set queue[rear] = value. Algorithm for DEQUEUE operation 1. Check whether queue is EMPTY. (front = -1) 2. If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!" and terminate the function. 3. If it is NOT EMPTY, then display queue[front] as deleted element, increment the front value by one (front ++). If we are deleting last element both front and rear are equal (front == rear), then set both front and rear to '-1' (front = rear = -1). mpl ntation; TIRUMALAENGINEERING COLLEGE iis > ¢ Insertion and deletions are performed at rear and front end respectively. If front and rear_ both are NULL, it indicates that the queue is empty. Initially struct node *front = NULL, *rear = NULL; Operation on Linked Queue: There are two basic operations which can be implemented on the linked queues. The operations are Enqueue and Dequeue. Enqueue function: Enqueue function will add the element at the end of the linked list. 1. Declare a new node and allocate memory for it. 2. If front == NULL, make both front and rear points to the new node. 3. Otherwise, add the new node in rear->next (end of the list) and make the new node as the rear node. i.e. rear = new node Dequeue function: Dequeue function will remove the first element from the queue. 1.Check whether the queue is empty or not 2.1f it is the empty queue (front == NULL), We can't dequeue the element. 3.Otherwise, Make the front node points to the next node. i.e front = front->next; if front pointer becomes NULL, set the rear pointer also NULL. Free the front node's memory. void dequeue() void enqueue(int value) f ig v X ; - oe struct node *ptr; struct node *newNode = malloc(sizeof(struct node)); if(front == NULL) uewNode->data = value; printf’ Queue is Empty"): newNode->next = NULL: else i if(front == NULL && rear == NULL) ptr = front; front = rear = newNode; front = front->next; else : free(ptr): { if(front == NULL) rear->next = newNode; ‘year = NULL: rear = newNode; y } } } Example; Enqueue() vee | ear Wh on | i | trent Vcar | rot J Lee | Le cay = ed | 10 | —» 20 | NULL | 5 4100 > 2 nd ears oe. 7 new nodo oO) now nade insert(20) bean ite nk insort(10) i. TIRUMALAENGINEERING COLLEGE _| Iv - Dequeue() ae roar [tron | [ear] front j [rear ae _ : eee ff. “ _ ~, al - | i] —-4 — a paseo i | —» 30 NULL 1 —— > 20 | i» 30 | wu | : PTR I 10 | Fact ed teen TYPES OF QUEUES: be classified into the following types: A queue data structure can 1. Circular Queue 2. Deque 3. Priority Queue 4. Multiple Queue~ Y rouble Eoded queue 7{ coRCULAR UEUEs: | once the queue is completely full, it's not possible to insert any more e actually e Ina Linear queue, elements. When we dequeue any element to remove it from the queue, we ar moving the front of the queue forward, but rear is still pointing to the last element of the queue, we cannot insert new elements. e Circular Queue is also a linear data structure, which follows the principle of FIFO(First In First Out), but instead of ending the queue at the last position, it again starts from the first position after the last, hence making the queue behave like a circular data structure. Operations on Circular Queue: The following are the operations that can be performed e. The new o enQueue(value): This function is used to insert the new value in the Queu element is always inserted from the rear end. deQueue(): This function deletes an element from the Queue. The deletion in a Queue always takes place from the front end. ce operation: The steps of enqueue operation are given below: Enqueue op First, we will check whether the Queue is full or not. oO o Initially the front and rear are set to -1. When we insert the first element in a Queue, front and rear both are set to 0. o From 2™ element onwards, When we insert a new element, the rear gets incremented, ie., rear=reartl. — Queue is not full: o Ifrear!=max- I, then rear will be incremented and the new value will be inserted at the rear end of the queue. o Iffront !=0 and rear = max - 1, it means that queue is not full, then set the value of rear to 0 and insert the new element there. Queue is full: o When front ==0 && rear = max-1, which means that front is at the first position of the Queue and rear is at the last position of the Queue. o front== rear + 1; TIRUMALAENGINEERING COLLEGE Circedlar Queue: Pcfinétion: — Efrteloa Queue a es restton is Connected po ~He tryst postion. So the Qete cee bebauer Uke a cercle- | re ina. clata shuckee in luthich — TE -follomsr FTF (Fisk in-fysk od] Principe, phere te Fast inststed element is Yemoued first + ylhere insertion 8 dime at pear ene and deletion ts cline at front-end. > TE is ued -b Eticeertly utz (ze memoxy by ting Emply spaces Created after deletion. Ofexdios: — t Engquexe 2+ De Quenre = Pisp oy Enqueue:— -Thés oft _ ato Queue { fot — enguene(, in€ eter) ’ if ( fimé ==0 YW itarz =MAK —1)I] Chont-arear-«1) print£(" Credo Queue ef full J} Else a War = (aCor+1) 7% MAX) CQ (rear = ftem ; Hf (font = = +) fit = 0; j } DeMtreue = — Remoting an elemen& af— tint position. Pi geaetiin:— step--- 1 Cf = =-1 print ( errcuberr (euewe ty empty”) Goto Step y Step —2:- glee if (fronts zreav) print ( deleted glement- és (font}) . SA- fmt =} Set rear = —f Exam ple:— Aambet reare-l MAX = 8, Enguecee (to) L wear = (yar ti) 7 MAX (Cnet + = (44172 2 OF3=0 LC) ee tym = O , rear =d. C@ (Jz lo Engucue C 20) Car = (reoer tt) Y. MIA X L x (ot!) % 2 = [75a] Os, wtavr=l).famt= | a eo CO(t)j= 20 Enqueue (20) yen Year = (veer +1) Y MAX dL b 2 (it %2 = 2% her AS mt rear a2, fone = 0 ( CQ(2) = 30 Dequene C ) 2 belebed element és to Prong Jo \™ar f front = (font +1) % MAK (é) = (04)y max = ly2 = i front = | Engueue (60) »- OMEN? rear= 2, front =| rok, _ rear = (rear 41)¥ MAK = O+% 2 =~ 3% 220 heb YEar=o , front = | CO (0) = 6o o Displagl):- This Operation & wed —b ot.poy the. slementT trom fymt- fp edn mn Citar GQuecté- Platt m:— t check i Creler queue us emply te fmt = = -! PynF “ Cneadar Queae o empty” 2. Olhkerwie Start = tom Frm Print gach element Move uUsmg t=(t47 max 3- step then f= 2 yea Program: — —eoeaoen Yojd ati splar C) f int ¢j if (fok= = -U) { Pink (" Crreker Queue empty Y $ EVe if v lic front j Tl srr) eaGeimax) Print (* %d\E”, COCy] j 4 Da a Scheduling :( APPLICATIONS OF QUEUE) e Scheduling is the process of allotting the CPU to the processes present in the ready queue. We also refer to this procedure as process scheduling. The operating system schedules the process so that the CPU always has one process to execute. Job Queue (In Disk) * This queue is known as the job queue, it contains all the processes or jobs in the list that are waiting to be processed. Job: When a job is created, it goes into the job queue and waits until it is ready for processing. Ready Queue (In Main Memory) ¢ The Stand-by queue contains al! the processes ready to be fetched from the memory, for execution. When the process is initiated, it joins the ready queue to wait for the CPU to be free. The operating system assigns a process to the executing processor from this queue based on the schcduline algorithm it implements. Block or Device Oucues (In Main Memory) * The processes which are blocked due to unavailability of an I/O device are added to this queue. Every device has its own block queue. aN : aN, y Long- / short- \, i term i term \scheduler/ \schedulen/ SN a N va Exit a Breadth-First Search (BFS) ¢ Breadth-First Search (BFS) is a graph traversal algorithm that explores all the neighboring nodes at the current depth before moving on to nodes at the next depth level. It starts at the root node (or any other randomly chosen node) and explores all the vertices in the graph. Breadth-First Search (BFS) Algorithm ¢ Step I: Define a queue with the same number of nodes as the graph. ° Step 2: Start traversal from starting point and put it into the Queue and count it as visited. * Step 3: Enqueue all the neighboring nodes of the visited node that have not been visited yet. ~rracg TIRUMALAENGINEERING COLLEGE @) ¢ Step 6: When the queue is empty, make the final spanning tree by removing unused lines from the gr Example Step 4: When there are no more vertices to visit . Dequeue that node (front Node) from the queue. ° Step 5: Repeat steps 3 and 4 until queue Is empty. Consider the following example graph to perform BES traversal Step 1: - Select the vertex A as starting point (visit A). - Insert A into the Queue, Queue Step 2: - Visit all adjacent vertices of A which are not visited (D, E, B). - Insert newly visited vertices into the Queue and delete A from the Queue.. Queue TIRUMALAENGINEERING COLLEGE aph. Step 7: - Visit all adjacent vertices of F which are not visited (there is no vertex). - Delete F from the Queue. Queue - Visit all adjacent vertices of G which are not visit , ed (there is no v - Delete G from the Queue. no vertex). Queue TIRUMALAENGINEERING COLLEGE Double Enckd Guecce (peque}] @) DE QUE :- “A Double ended gueue (Deque] ty a linear clata Shu Clure ‘thick —anserton ayel cleletin = Gan. be. Pevteemed Pram koth gnels- » Front ene ° Rear ene So glements Gan be added (@) remoued ton steer Steb.. Reque cn be Used bey a both Slack and Oltece . Operations t- Fnseré of Frnt a taser at rear — This is Gitar “fo Enauedd in quewe 2- pelele tom tink — This is similar 4o Pequel) iy Queue u pebele tam far 5: disphy — This is Srmilay to Sespley 6) cpercction in Pieue. fork end - bear ene “Tapes of Deque:- raserH a | | | b (nse at t Inpub restyicted Deque bee 7 Sle let, ° Inser¥a) allowed ak only me enel - Deletim allowed at foth endc ~ end Tea eng a. Cut put Restrected deque mak " df ° heletin allowed at only me €énd 7 ! | | | <— e Tnsexttr) allowed at- both enels. ( : / "éey¢ celetion Pr9ram ie F i hear ==MA x) prt (« Deque oues-Floes “) Z j Elie if (front ==-1 yg rears -t) ¢ Front = Year =o 3 eqmelies]= ee ; 5 else v Year = heart] ; ag lrear] = els; $ j ef LLT fe f=2o Unie insertion Cink ele) Engueue (12) Er(puené (ro) hel [I Oo } 4 20 Yz| 10 Deletim at Frnt end:- Prlggeethm te alg (max) -frowt=-l 7 rear=—| Ses \ t- Check 7 clegue ts empty it (font ==-1) + undertlocs d+ print © oleleted element at- oy (font ]” 3- te deque Gnsists of aly me element if- [front == teas) Sth fyb =vewr= —| q- spe increment = -fipnlb-= fink +) S- EANID-