You are on page 1of 55
What is Stack? * A stack is an Abstract Data Type (ADT), commonly used in most programming languages. * It is an ordered group of homogeneous items of elements. * Stack is a linear data structure which follows a particular order in which the operations are performed. + The order may be LIFO(Last In First Out) or FILO(First In Last Out). * Astack can be implemented by means of Array, Structure, Pointer, and Linked List. * Stack can either be a fixed size one or it may have a sense of dynamic resizing. * Stack performed Push, Pop(), Peek(), IsFull() and IsEmpty( operations. Positions of the Stack Position of Top Status of Stack Stack is Empty Only one element in Stack Stack is Full Overflow state of Stack Operation 1: PUSH() Push: The process of putting a new data element onto stack is known as a Push Operation. gorithm Steps: Step 1 ~ Checks if the stack is full. Step 2 — If the stack is full, produces an error and exit. Step 3 ~ If the stack is not full, increments top to point next empty space. Step 4 — Adds data element to the stack location, where top is pointing « ~\ Push Operation Step 5 — Returns success. bool Stack: :push(int ») AF (top >= (MAK - 1)) { ‘cout << “Stack Overflow"; return false; 3 toy > Pp else { al++top] = xs cout info = x; Stack operations ona Linked List newNode->link=head; head = newNode; Push / Pop } ¥ beginning cod Stack Operations Using Linked List int pop) { int x = head->info; head = head->link; return x; } Advantages of Stack using Linked Organization + Astack can be easily implemented through the linked list. * The main advantage of using linked list over an arrays is that it is possible to implements a stack that can shrink or grow as much as needed. + In using array will put a restriction to the maximum capacity of the array which can lead to stack overflow. ‘swe, Ss = 10p of the stack + Here each new node will be dynamically allocate. * so overflow is not possible. top of the stack Infix & Postfix Expression > Infix expression: The expression of the form a op b. (i.e. 3+2) When an operator is in-between every pair of operands. > Postfix expression: The expression of the form a b op. (i.e. 32+) When an operator is followed for every pair of operands. v Why postfix representation of the expression? The compiler scans the expression either from left to right or from right to left. Procedure for Infix to Postfix Conversion 1. Scan the Infix string from left to right. 2. Initialize an empty stack. If the scanned character is an operand, add it to the Output Postfix string 4, Ifthe scanned character is an operator and if the stack is empty push the character to stack. 5. If the scanned character is an Operator and the stack is not empty, compare the precedence of the character with the element on top of the stack 6. _ Iftop Stack has higher precedence over the scanned character, pop the stack. If top Stack has lower precedence over the scanned character, push into stack. If top Stack has same precedence over the scanned character, pop the stack. Repeat this step until the stack is not empty and top Stack has precedence over the character 8. Repeat 4 and 5 steps till all the characters are scanned. 9. After all characters are scanned, we have to add any character that the stack may have to the Postfix string. Procedure for Infix to Postfix Conversion 1. Scan the Infix string from left to right. 2. Initialize an empty stack. If the scanned character is an operand, add it to the Output Postfix string 4, Ifthe scanned character is an operator and if the stack is empty push the character to stack. 5. If the scanned character is an Operator and the stack is not empty, compare the precedence of the character with the element on top of the stack 6. _ Iftop Stack has higher precedence over the scanned character, pop the stack. If top Stack has lower precedence over the scanned character, push into stack. If top Stack has same precedence over the scanned character, pop the stack. Repeat this step until the stack is not empty and top Stack has precedence over the character 8. Repeat 4 and 5 steps till all the characters are scanned. 9. After all characters are scanned, we have to add any character that the stack may have to the Postfix string. Example of Infix to Postfix Conversion Exampl A+B*C-(DIE-F)*G)"H ‘Stack Empty Empty + + + + +e +64 +64 + + +e Input A+(B*C-(D/E-F'G)"H +(8°C-(D/E-FG)"H (8°C-(D/E-F'G)"H BC-O/E-AGH *C(O/E-FYG)H CO /E-AGH -(DA-FYG)"H DE-FYGH D/E-AYGH EACH EACH -FYGH FYG)H a8 a8 8c nace pct ABCD ABCD ABC'DE ABC*DE/ Continue... Example of Infix to Postfix Conversion Exampl A+(B*C-(DE-F)*G)*H stack Input output +66 FYGH ABC*DE/ +e y6H ABCYDE/F + “or ABCYDEVF +e oH ABCYDEF. + vt ABCDEFF-G + H ABCYDE/F-G* * 4 ABC*DE/F-G*- ” ind ABCYDE/F-G*-H Empty End ABC*DE/F-G*-H"+ Application of Infix to Postfix Conversion + Infix expressions are readable and solvable by humans + We can easily distinguish the order of operators, and also can use the parenthesis to solve that part first during solving mathematical expressions. + The computer cannot differentiate the operators and parenthesis easily, that’s why postfix conversion is needed. Recursion Basic Ideas We have a bigger problem whose solution is difficult to find. We divide/decompose the problem into smaller (sub) problems. Keep on decomposing until we reach to the smallest sub-problem (base case) for which a solution is known or easy to find. Then go back in reverse order and build upon the solutions of the sub-problems. Recursion is applied when the solution of a problem depends on the solutions to smaller instances of the same problem. The concept of recursion is established on the idea that a problem can be solved much easily and in lesser time if it is represented in one or smaller versions. What is mean by Recursion? Definition: + A programming technique in which a function calls itself is known as recursion. + A function that calls itself is called recursive function. LX Sev Tet om gare dolar} Application of Recursion 1. Recursion is Example of STACK: bo find factt5) =F ag, + Last in first out (LIFO) data structure * Push operation adds new element at the top + Pop operation removes the top element 2. Parsing in Compiler, Data Mining, Data Retrieval etc. 3. Math Functions or Number Sequences. 4. Analysis of Social Networks Introduction of Queue + A Queue is a linear & abstract data structure which follows a particular order in which the operations are performed. * The order is First In First Out (FIFO) which means that element inserted first will be removed first. + Front points to the beginning of the queue and Rear points to the end of the queue. * One end is always used to insert data (enqueue) and the other is used to remove data dequeue). Deletion, Insertion Real Life Applications of Queue Hi hd Queue Representation + The process to add an element into queue is called Enqueue. + The process of removal of an element from queue is called Dequeue. eerie eet cieaton Working of Queue & CITLIT] J Queue operations work as follows: + two pointers FRONT and | REAR a «| FRONT. track the first element of the queue «| REAR track the last elements of the queue ‘enqueuel 5 the operation for adding an element into Queve dequeuel | 5 the operation for removing an element from Queue initially, set value of FRONT and REAR to-1 Types of Queue 1. Simple Queue + The simple queue is a normal queue where insertion takes place at the FRONT of the queue + Deletion takes place at the END of the queue. a aay Enqueue 2. Circular Queue * Ina circular queue, the last node is connected to the first node. * Circular queue is also called as Ring Buffer. * Insertion in a circular queue happens at the FRONT and deletion at the END of the queue. Types of Queue Continue.. 3. Priority Queue * Ina priority queue, the nodes will have some predefined priority. + Insertion in a priority queue is performed in the order of arrival of the nodes. + The node having the least priority will be the first to be removed from the priority queue. 4. Dequeue (Doubly Ended Queue) *In a Double Ended Queue, insertion and deletion operations can be done at both FRONT and END of the queue. soo cme Area scour arr Queue as an ADT / Operations Performed on Queue A queue is an object or more specifically an abstract data structure(ADT) that allows the following operations: 1, Enqueue: Add an element to the end of the queue. 2. Dequeue: Remove an element from the front of the queue. 3. IsEmpty: Check if the queue is empty. 4. IsFull: Check if the queue is full. 5. Peek: Get the value of the front of the queue without removing it. Applications of Queue in Data Structure Computer Science Applications 1. Operating System Task Scheduling. Print lines of documents. =. Printer shared between computers. Shared resources usage (CPU, Memory ete.) Analysis of traffic Telephone Operators: Handling calls to toll-free numbers. SE Ge J. \= Gk Difference between Stack & Queue STACK QUEUE Objects are inserted and removed at | Objects are inserted and the same end. removed from different ends. in stacks only one pointer is used. It | In queues, two different pointers points to the top of the stack are used for front and rear ends. In stacks, the last inserted object is_| In queues, the object inserted first to come out first is first deleted Stacks follow Last in First Out (LIFO) | Queues following First in First order. Out (FIFO) order Stack operations are called push _ | Queue operations are called and pop, enqueue and dequeue Stacks are visualized as vertical | Queues are visualized as collections. horizontal collections. Collection of dinner plates at a wedding reception is an example of stack People standing in a file to board a bus is an example of queue. Introduction of Queue Using Array ‘A queue data structure can be implemented using one dimensional array. The queue implemented using array stores only fixed number of data values. The implementation of queue data structure using array is very simple. Just define a one dimensional array of specific size and insert or delete the values into that array by using FIFO (First In First Out) principle with the help of variables ‘front! and ‘rear’. Initially both ‘front’ and ‘rear’ are set to -1. ‘Whenever, we want to insert a new value into the queue, increment ‘rear’ value by one and then insert at that position. Whenever we want to delete a value from the queue, then delete the element which is at !front’ position and increment "front! value by one. 2 ase aes Queue as an ADT / Operations Performed on Queue A queue is an object or more specifically an abstract data structure(ADT) that allows the following operations: 1. Enqueue: Add an element to the end of the queue. 2. Dequeue: Remove an element from the front of the queue 3. IsEmpty: Check if the queue is empty. 4, IsFull: Check if the queue is full 5. Peek: Get the value of the front of the I queue without removing it. memset Operations Performed Queue Using Array 1. Insertion: Step 1: If REAR = MAX — 1 then Write “Queue is Overflow” Goto step 4 [End of IF] Step 2: IF FRONT=-1 and REAR=-1 SET FRONT=REAR=0 ELSE SET REAR=REAR+1 [END OF IF] Step 3: SET QUEUE [REAR] = NUM Step 4: EXIT ato} Al lz) Ag] ala) Ao) All a2) Ais) ala) F=R=0 Alo} Ally a2) Als} ala) F=0 le Operations Performed Queue Using Array 2. Deletion: Step 1: IF FRONT = -1 OR FRONT>REAR Write “Queue is Underflow” ELSE SET VAL=QUEUE [FRONT] FRONT = FRONT +1 [END OF IF] Step 2: EXIT Alo) * Al2] a3) Atal F20 Rel alo} Atl) lz] a3) Atal Example of Queue Using Array Enguene(s) Empeaue (5) Emguaue(9) front 2 t enqueue (ny Engeene (2) Disadvantages of Linear Queue * Ina normal Queue Data Structure, we can insert elements until queue becomes full. * But once the queue becomes full, we can not insert the next element until all the elements are deleted from the queue. Queve is Full Queve is Full (Even three elements are deleted); LL front rear Introduction of Circular Queue * Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle. * The last position is connected back to the first position to make a circle. * It is also called ‘Ring Buffer’. The circular queue work as follows: ‘= two pointers | FRONT and REAR ‘+ FRONT track the first element of the queue ‘+ | REAR. track the last elements of the queue « initially, set value of FRONT |and | REAR |to -1 Operations Performed on Queue 1, Enqueue: Adding an element in the queue if there is space in the queue. 2. Dequeue: Removing elements from a queue if there are any elements in the queue 3. Front: Get the first item from the queue. (Deletion) 4. Rear: Get the last item from the queue. (Insertion) 5. Isempty/isfull: Checks if the queue is empty or full Enqueue Operation . Check if the queue is full. . For the first element, set value of FRONT to 0. . Circularly increase the REAR index by 1 . Add the new element in the position pointed to by REAR. Dequeue Operation 1. Check if the Queue is empty. 2. Return the value pointed by front 3. Circularly increase the FRONT index by 1 4. For the last element, reset the values of FRONT and REAR to -1 Example of Circular Queue Example: Consider the following circular queue with N = 5. 1. Initially, Rear = 1, Front = 1. 4. Insert 20, Rear = 3, Front = 1. y 2 Front , h . /, Rear 2. Insert 10, Rear = 1, Front = 1. 5. Insert 70, Rear = 4, Front = 1. eS ass Re 3. se 0 Rear = 2, Front = 1. 6. Delete front, Rear = 4, Front = 2. From Roar Loy 7 Roar Example of Circular Queue Continue.. 7. Insert 100, Rear = 5, Front = 2. 10. Delete front, Rear = 1, Front = 3. ga) So 8. Insert 40, Rear = 1, Front = 2. 11. Delete front, Rear = 1, Front = 4. 2 fe ~ for Yo Tore Vol GCy) ROY 9. Insert 140, Rear = 1, Front = 2. 12. Delete front, Rear = 1, Front = 5. As Front= Rear + 1, so Queue overflow, y= Pear y B ies y) Applications of Circular Queue + Memory management: Circular Queue is used in memory management. + Process Scheduling: ACPU uses a Queue to schedule processes. + Traffic Systems: Queues are also used in traffic systems. Linear VS Circular Queue LINEAR QUEUE VERSUS CIRCULAR QUEUE ia tous) Forum eee Perr PMintesa rraniurachr tint elements similar to a real world queue Sooo oreo LS Tonos ants) oat IVa goKannT 5 A 5 Peeeeeeee Soares! Mo! Introduction of Double Ended Queue * Double Ended Queue is also a Queue data structure in which the insertion and deletion operations are performed at both the ends (front and rear). + That means, we can insert at both front and rear positions and can delete from both front and rear positions. Complexity ‘+ Insertion or deletion in the middle is O(n) ‘+ The time complexity of random access by index is O(1) ‘* time complexity of al enque(insert)/deque(delete) operations is O(1) Types of Double Ended Queue Double Ended Queue can be represented in TWO ways: 1. Input Restricted Double Ended Queue 2. Output Restricted Double Ended Queue ‘Type 1: Input Restricted Double Ended Queue: 1. The insertion operation is performed at only one end. = T 1 4 2. Deletion operation is performed at both the ends. =¢ CPEEEET >| ‘Type 2: Output Restricted Double Ended Queue: 1. The deletion operation is performed at only one end 2. Insertion operation is performed at both the ends. 1, Operations Performed on Queue push_back : inserts element at back . push_front : inserts element at front pop_back : removes last element |. pop_front : removes first element . get_back : retums last element get_front : returns first element . empty : returns true if queue is empty . full : returns true if queue is full © Insertion at rear end © Insertion at front end * Deletion at front end * Deletion at rear end Applications of Double Ended Queue A-Steal job scheduling algorithm © The A-Steal algorithm implements task scheduling for several processors(multiprocessor scheduling). ‘© The processor gets the first element from the deque. © When one of the processor completes execution of its own threads it can steal a thread from another processor. ‘© It gets the last element from the deque of another processor and executes it.

You might also like