Download presentation
Presentation is loading. Please wait.
Published byBenedict Smith Modified over 6 years ago
1
UNIT-2 To be able to implement Stack ADT using arrays.
To be able to implement Stack ADT using linked list. To analyze various application of stacks. To implement infix to postfix conversion. To be able to implement Queue ADT using arrays. To be able to implement Queue ADT using linked list. To understand the concept of Circular Queue. To implement Circular Queue ADT. To understand the concept of Double Ended Queue. To be able to implement Double Ended Queue ADT using arrays. To be able to implement Double Ended Queue ADT using linked list.
2
STACKS Linear list. One end is called top. Other end is called bottom.
Additions to and removals from the top end only.
3
STACK ADT A stack is a Last In First Out (LIFO) data structure in which all insertions and deletions are takes place at one end, called the top. Stack maintains a variable called top, which keeps track of the top most element in the stack. Any insertions or deletions should be based upon the value of top. In the stack, the elements are removed in the reverse order of that in which they were added to the stack that is last element inserted is to be deleted first. Basic Stack Operations: push :To insert an item into stack pop :To delete an item from stack traversal :To display an items isFull :To know whether the stack is full or not isEmpty :To know whether the stack is empty or not 3
4
STACK ADT Example 1: When the elements are inserted in the order as A,B,C,D then the size of the stack is 4 and the top most element in the stack is D. When deletion operation is performed on stack continuously then the order in which the elements are deleted is D,C,B,A. 4
5
STACKS Standard operations: IsEmpty … return true iff stack is empty
IsFull … return true iff stack has no remaining capacity Top … return top element of stack Push … add an element to the top of the stack Pop … delete the top element of the stack The decision whether to use the left or right end of the linear list as the stack top is made on the basis of efficiency of resulting stack methods. The complexity of empty(), size() and top() are independent of the choice. 5
6
STACKS Stack CreateS(maxStackSize) ::=
#define MAX_STACK_SIZE 100 /* maximum stack size */ typedef struct { int key; /* other fields */ } element; Element stack[MAX_SSTACK_SIZE]; Int top = -1; Boolean IsEmpty(stack) ::= top<0; Boolean IsFull(Stack) ::= top >= MAX_STACK_SIZE – 1;
7
STACKS ADT Stack is Object: a finite ordered list with 0 / more elements. Functions: for all stack belong Stack, item belong element, maxStackSize belongs positive integer. Stack Create(maxStackSize)::= create an empty stack whose maximum size is maxStackSize Boolean IsFull(stack ,maxStackSize)::= if (number of elements in stack == maxStazkSize) return TRUE else return FALSE Stack Push(stack) ::= if (IsFull(stack)) stackFull else insert item into top of stack and return Boolean IsEmpty(stack) ::= if (stack == CreateS(maxStackSize)) return TRUE else return FALSE Element Pop(stack) ::= if (IsEmpty(stack)) return else remove and return the element at the top of the stack The decision whether to use the left or right end of the linear list as the stack top is made on the basis of efficiency of resulting stack methods. The complexity of empty(), size() and top() are independent of the choice. 7
8
STACKS Use a 1D array to represent a stack.
Stack elements are stored in stack[0] through stack[top]. The decision whether to use the left or right end of the linear list as the stack top is made on the basis of efficiency of resulting stack methods. The complexity of empty(), size() and top() are independent of the choice. 8
9
STACKS Derive From arrayList a b c d e 1 2 3 4 5 6 Push(theElement) => if full then either error or increase capacity and then add at stack[top+1] Suppose we increase capacity when full O(capacity) time when full; otherwise O(1) Pop() => if not empty, delete from stack[top] O(1) time
10
STACKS void push(element item) {/* add an item to the global stack */
top 1 2 3 4 void push(element item) {/* add an item to the global stack */ if (top >= MAX_STACK_SIZE - 1) StackFull(); /* add at stack top */ stack[++top] = item; }
11
STACKS a b c d e 1 2 3 4 element pop() { if (top == -1)
1 2 3 4 element pop() { if (top == -1) return StackEmpty(); return stack[top--]; }
12
STACKS StackFull() void StackFull() {
fprintf(stderr, “Stack is full, cannot add element .”); exit(EXIT_FAILURE); }
13
STACKS Stack Using Dynamic Arrays void Stack CreateS( ) ::=
typedef struct { int key; /* other fields */ } element; element *stack; MALLOC (stack , sizeof(*stack)); Int capacity= 1; Int top = -1; Boolean IsEmpty(Stack) ::= top<0; Boolean IsFull(Stack) ::= top >= capacity – 1; void
14
StackFull()/Dynamic Array
STACKS StackFull()/Dynamic Array Use a variable called capacity in place of MAX_STACK_SIZE Initialize this variable to (say) 1 When stack is full, double the capacity using REALLOC This is called array doubling
15
StackFull() STACKS void StackFull() {
REALLOC(stack, 2*capacity*sizeof(*stack); capacity *= 2; }
16
STACK ADT IMPLEMENTATION Stack can be implemented in two ways:
using arrays using linked list 16
17
STACK ADT USING ARRAYS STACK IMPLEMENTATION USING ARRAYS Procedure:
Initialize the stack by assigning -1 to the top variable to indicate that the array based stack is empty. A top is an integer value, which contains the array index for the top of the stack. Each time data is pushed or popped, top is incremented or Decremented accordingly, to keep track of the current top of the stack. Stacks implemented as arrays are useful if a fixed amount of data is to be used. 17
18
Algorithm for inserting an element into the stack
STACK ADT USING ARRAYS Algorithm for inserting an element into the stack push() 1. if top>=size then print “stack is full” 2. else read item top=top+1 stack[top]=item endif 3. stop The first step of this algorithm checks for an overflow condition. Overflow occurs when we are trying to insert an item into a stack which is full. If the top value reaches to maximum size of the stack then items cannot be inserted into the stack i.e. stack is full. Otherwise top is incremented by one and item is inserted into the stack. 18
19
STACK ADT USING ARRAYS Push Functon void push() { int ele;
if(top==SIZE-1) printf("\n stack is full(overflow)\n"); return; } else printf("enter the element to push:"); scanf("%d",&ele); top++; stack[top]=ele;
20
Algorithm for deleting an element from the stack
STACK ADT USING ARRAYS Algorithm for deleting an element from the stack pop() 1. if top = -1 then print “stack is empty” 2. else 1. item = stack[top] 2. top=top-1 3.endif 4.stop The first step of this algorithm checks for underflow condition. If the top value is -1 then stack is known as underflow or empty. Takeout the element from the location where the top is pointing and store it in the variable then decrement top by one. 20
21
STACK ADT USING ARRAYS POP Functon void pop() { if(top==-1)
printf("\n stack is empty(underflow)\n"); else printf("the pop element is:%d",stack[top]); top--; }
22
STACK ADT USING ARRAYS traversal() 1. if top = -1
Algorithm for displaying an elements of the stack traversal() 1. if top = -1 1.print “stack empty” 2. else 1. for(i = top; i >= 0;i--) 1.print “stack[i]” 3.endif 4. stop void display() { if(top==-1) printf("\n stack is empty(underflow)"); return } printf("\n the elements in stack are:\n"); for(i=top;i>=0;i--) printf("->%d",stack[i]); If the top value is -1 then the stack is empty. If the stack is not empty, assign a top value to variable i, display the item which is pointed at stack[i] , decrement the top value by one and repeat this process until top becomes zero. C program example1 , also show error simulation 22
23
STACK ADT USING LINKED LIST
STACK IMPLEMENTATION USING LINKED LIST Implementing stacks as linked lists provides a feasibility on the number of nodes by dynamically growing stacks, as a linked list is a dynamic data structure. The stack can grow or shrink as the program demands it to. Disadvantage of using an array to implement a stack or queue is the wastage of space. A variable top always points to top element of the stack. top = NULL specifies stack is empty. 23
24
STACK ADT USING LINKED LIST
Example: The following list consists of five cells, each of which holds a data object and a link to another cell. 24
25
STACK ADT USING LINKED LIST
Push function POP function void push() { struct node*temp; temp=(struct node*)malloc(sizeof(struct node)); printf("\n enter data of item:"); scanf("%d",&temp->data); temp->link=top; top=temp; } void pop() { struct node*temp; if(top==NULL) printf("\n stack is empty \n"); else temp=top; printf("popped item is %d \n",temp->data); top=top->link; free(temp); } 25
26
STACK ADT USING LINKED LIST
Traversal function void display() { struct node*temp; temp=top; if(top==NULL) printf("stack is empty \n"); else printf("stack elements:\n"); while(temp!=NULL) printf("->%d",temp->data); temp=temp->link; } C program example2 , also show error simulation
27
STACK APPLICATIONS APPLICATIONS
Stacks are used in conversion of infix to postfix expression. Stacks are also used in evaluation of postfix expression. Stacks are used to implement recursive procedures. Stacks are used in compiler design. 27
28
STACK APPLICATIONS TYPES OF EXPRESSIONS
Arithmetic expressions can be represented in three ways: Infix notation: The operator is in between the two operands. Examples: A+B Prefix (Polish notation): The operator precedes the operands. Examples: +AB +23 Postfix (Reverse Polish Notation): The operator follows the operands. Examples: AB 28
29
STACK APPLICATIONS CONVERSIONS
Consider the infix expression: * (5 – 7) / 9 Let us insert implicit parentheses (2 + ((3 * (5 – 7)) / 9)) Transfer the operators to the beginning of parentheses (+ 2 (/ (* 3 (– 5 7)) 9)) Remove the parentheses: / * 3 – This is the equivalent prefix expression. Transfer the operators to the end of parentheses (2 ((3 (5 7 –) *) 9 /) +) Remove the parentheses: – * 9 / + This is the equivalent postfix expression. 29
30
STACK APPLICATIONS Algorithm to convert infix expression to Postfix:
Initialize an empty stack. Repeat the following process until the end of the infix expression. Get next input token (constant, variable, arithmetic operator, left parenthesis, right parenthesis) in the infix expression. If the token is A left parenthesis: Push it onto the stack. A right parenthesis: Pop and display stack elements until a left parenthesis is on the top of the stack. Pop the left parenthesis also, but do not display it. An operator: While the stack is nonempty and token has higher or equal priority than the stack’s top element, pop and display. Push token onto the stack. An operand: Display it. When the infix expression is reached to the end, pop and display stack items until the stack is empty. (Note: Left parenthesis in the stack has lowest priority) 30
31
STACK APPLICATIONS 31
32
STACK ADT 1. Algorithm for postfix conversion:
void postfix(char inf[15]) Step 1: repeat the steps a to c until inf[i]!='\0' a. check if infix expression is opening brace push it onto stack check if(inf[i]='(‘) push(inf[i]) b. check if infix expression is alphabetic character add it to postfix express if(isalpha(inf[i])) pf[j++]=inf[i] c. check if infix expression is closing brace if(inf[i]==')') repeat 1 to 2 until stack[top]!=opening brace 1.pf[j++]=pop() 2.x=pop() Otherwise repeat 1 to 2 until prec(stack[top])>=prec(inf[i]) 2.push(inf[i]) Step 2: repeat the steps a to b until top!=-1 a.pf[j++]=pop() b.pf[j]='\0' step 3: stop 32
33
STACK ADT 2. Algorithm for push operation on stack:
Step 1:increment top by 1 Step 2: stack[++top]=y Step 3:stop 3. Algorithm for pop operation on stack: Step 1:return stack[top] Step 2: decrement top by 1 4. Algorithm for finding precedence of operators : Step 1:check if (c=='*' || c=='/' || c=='%') return(5) step 2:check if (c=='+' || c=='-') return(3) Step 3:if(c=='(') return(1) step 4:stop 33
34
STACK ADT 5. Algorithm for main function : Step 1:start
Step 2: read infix expression Step 3:call postfix(infix) Step 4:print postfix expression result Step 5:stop 34
35
STACK APPLICATIONS Postfix conversion function
void postfix(char inf[15]) { char x; for(i=0;inf[i]!='\0';i++) if(inf[i]=='(') push(inf[i]); else if(isalpha(inf[i])) pf[j++]=inf[i]; else if(inf[i]==')') while(stack[top]!='(') pf[j++]=pop(); x=pop(); } else { while(prec(stack[top]>=prec(inf[i]))) pf[j++]=pop(); push(inf[i]); } }//end of for while(top!=-1) pf[j]='\0'; }//end of postfix() void push(int y) { stack[++top]=y; }//end of push() int pop() { return(stack[top--]); }//end of pop()
36
STACK APPLICATIONS Precedence function int prec(char c) {
if(c=='*' || c=='/') return(5); else if(c=='+' || c=='-') return(3); else if(c=='(') return(1); }//end of prec() C program example3 , also show error simulation
37
STACK APPLICATIONS Algorithm to evaluate Postfix Expression:
Initialize an empty stack. Do Get next token (constant, arithmetic operator) in postfix expression. If token is an operand, push it on the stack. If token is an operator do the following: Pop top two values from the stack. (If the stack does not contain two items, report error.) Apply operator token to these two values. Push the resulting value onto the stack. Continue the process until the end of the expression is encountered. The value of the expression is on the top of the stack (and stack should contain only this value). 37
38
STACK APPLICATIONS C program example4 , also show error simulation 38
39
STACK APPLICATIONS Postfix evaluation function case '-':push(a-b);
break; case '*':push(a*b); case '/':push(a/b); default: printf("invalid operator\n"); }//end of switch }//end of else }//end of for printf("value of expression %f",stack[top--]); }//end of evaluate() void evaluate(char pf[15]) { float a,b,x; for(i=0;pf[i]!='\0';i++) if(isalpha(pf[i])) printf("enter value of %c",pf[i]); scanf("%f",&x); push(x); }//end of if else//if operator b=pop(); a=pop(); switch(pf[i]) case '+':push(a+b); break; void push(float y) { stack[++top]=y; } float pop() return(stack[top--]);
40
STACKS Direct applications Indirect applications
Applications of Stacks Direct applications Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in the Java Virtual Machine Indirect applications Auxiliary data structure for algorithms Component of other data structures 40
41
STACK APPLICATIONS Demonstration of Manual infix to postfix conversion
Step 1 A + B * C by placing paranthesis results ( A + ( B * C ) ) Step 2 moves the multiply operator after C ( A + (B C *) ) moves the addition operator to between the last two closing parentheses. This change is made because the closing parentheses for the plus sign is the last parenthesis. We now have ( A ( B C * ) + ) Finally ,step 3 removes the parentheses A B C * +
42
Example 4 converting infix expression to postfix expression
STACK APPLICATIONS Infix Transformations A + B * C – D / E Converts to A B C * + D E / - Above transformation is illustrated in following figure. Example 4 converting infix expression to postfix expression
43
STACK APPLICATIONS Evaluation of Postfix Expression
In evaluation of postfix expression, it is the operands that are pushed on to the stack. The postfix expression is scanned from left to right. Any operands encountered are pushed on to the stack. When an operator is encountered, the top two operands are popped from the stack. The operation is performed and the result is pushed back on to the stack. In the end, the final value is popped from the stack and returned.
44
Example 5 evaluation of postfix expression
STACK APPLICATIONS Evaluation of Postfix Expression For example given expression is A B C + * And assuming that A is 2, B is 4, and C is 6 , the following figure shows the evaluation of postfix expression. Example 5 evaluation of postfix expression
45
Queues Definition A queue is a order / linear list in which data can be inserted at one end, called the rear, and deleted from the other end, called the front. It is a first in–first out (FIFO) restricted data structure. A queue is same as Ex: 1)a line of people waiting for a bus at bus station. 2)a list of waiting jobs to be processes by a computer. The fig-1 below shows two examples of a queue. A) A queue of people B) a computer queue 45
46
Queues ADT Queue is Object: a finite ordered list with 0 / more elements. Functions: for all queue belong Queue, item belong element, maxQueueSize belongs positive integer. Queue Create(maxQueueSize)::= create an empty queue whose maximum size is maxQueueSize Boolean IsFull(queue ,maxQueueSize)::= if (number of elements in queue == maxQueueSize) return TRUE else return FALSE Queue AddQ(queue , item) ::= if (IsFullQ(queue)) queueFull else insert item at rear of queue and return queue Boolean IsEmptyQ(queue) ::= if (queue == CreateQ(maxQueueSize)) return TRUE else return FALSE Element DeleteQ(queue) ::= if (IsEmptyQ(queue)) return else remove and return the item at front of queue 46
47
Other end is called rear. Additions are done at the rear only.
Queues Linear list. One end is called front. Other end is called rear. Additions are done at the rear only. Removals are made from the front only. By comparison, in a stack adds and removes are to/from the same end of he list.
48
Bus Stop Queue Bus Stop front rear rear rear rear rear
49
Bus Stop Queue Bus Stop front rear rear rear
50
Bus Stop Queue Bus Stop front rear rear
51
Bus Stop front rear rear Bus Stop Queue
This is FIFO queue. Some real life queues are not FIFO. Removal from a queue may be done by priority rather than by arrival time order. For example, loading into a plane– first class, frequent fliers, by rows from back of plane rather than by order in which you arrive at the departure gate.
52
Revisit Of Stack Applications
Applications in which the stack cannot be replaced with a queue. Parentheses matching. Towers of Hanoi. Switchbox routing. Method invocation and return. Try-catch-throw implementation. Application in which the stack may be replaced with a queue. Rat in a maze. 2. Results in finding shortest path to exit.
53
Wire Routing Represent as a grid in which components and already placed wires are denoted by blocked grid positions.
54
Could use rat in a maze animation from Web site instead.
Lee’s Wire Router start pin end pin Could use rat in a maze animation from Web site instead. Blue squares are blocked squares. Orange squares are available to route a wire. A queue of reachable squares is used. The queue is initially empty, and the start pin square/cell is the examine cell. This cell has a distance value of 0. Unreached unblocked squares adjacent to the examine cell are marked with their distance (this is 1 more than the distance value of the examine cell) and added to the queue. Then a cell is removed from the queue and made the new examine cell. This process is repeated until the end pin is reached or the queue becomes empty. Cells become examine cells in order of their distance from the start pin. Label all reachable squares 1 unit from start.
55
start pin end pin 1 1 Lee’s Wire Router
Label all reachable unlabeled squares 2 units from start.
56
start pin 2 2 end pin 1 1 2 2 2 Lee’s Wire Router
Label all reachable unlabeled squares 3 units from start.
57
start pin 3 3 2 2 end pin 1 1 2 2 2 3 3 Lee’s Wire Router
Label all reachable unlabeled squares 4 units from start.
58
start pin 4 3 3 2 2 end pin 1 1 2 2 2 3 4 3 4 4 4 Lee’s Wire Router
Label all reachable unlabeled squares 5 units from start.
59
Lee’s Wire Router 5 start pin 4 5 3 3 2 2 end pin 1 1 2 2 2 3 4 3 4 5 4 4 5 5 5 Label all reachable unlabeled squares 6 units from start.
60
Lee’s Wire Router 6 5 6 start pin 4 5 3 3 2 2 end pin 1 1 2 2 2 6 3 4 3 4 5 6 4 4 5 6 5 6 5 6 6 End pin reached. Traceback.
61
Lee’s Wire Router 6 5 6 start pin 4 5 3 3 2 2 end pin 1 1 1 2 2 2 2 6 3 4 3 3 4 4 5 5 6 4 4 5 6 5 6 5 6 6 End pin reached. Traceback.
62
Queue Operations IsFullQ … return true iff queue is full IsEmptyQ … return true iff queue is empty AddQ … add an element at the rear of the queue DeleteQ … delete and return the front element of the queue
63
Queue in an Array Use a 1D array to represent a queue. Suppose queue elements are stored with the front element in queue[0], the next in queue[1], and so on.
64
DeleteQ() => delete queue[0]
Queue in an Array 1 2 3 4 5 6 a b c d e DeleteQ() => delete queue[0] O(queue size) time AddQ(x) => if there is capacity, add at right end O(1) time
65
Queues Queue CreateQ(maxQueueSize) ::=
#define MAX_QUEUE_SIZE 100 /* maximum queue size */ typedef struct { int key; /* other fields */ } element; element stack[MAX_QUEUE_SIZE]; int rear = -1; int front = -1; Boolean IsEmptyQ(queue) ::= front == rear; Boolean IsFullQ(queue) ::= rear == MAX_QUEUE_SIZE – 1; 65
66
Queues Add to a Queue void addq(element item) {
/* add an item to the queue */ if(rear == MAX_QUEUE_SIZE-1) queueFull(); queue[+rear] = item; } 66
67
Queues Delete from a queue element deleteq() {
/* remove element at the front of the queue */ if (front == rear) return queueEmpty(); /* return an error key */ return queue[ ++ front ] } 67
68
Queues Objectives: Queue Operations Queue Linked List Design
Queue Functions Queue Demonstration 68
69
Queues Queue operations: The two basic queue operations:
1)Insertion operation (enqueue) 2)Deletion operation (dqueue) Data can be inserted at the rare in queue Data can be deleted at front in queue 69
70
QUEUE ADT IMPLEMENTATION Queue can be implemented in two ways:
using arrays using linked list 70
71
Queues using arrays Enqueue
We can also implement queue using arrays. There are mainly two functions in implementation of queue: 1) enqueue 2) dequeue Enqueue An enqueue to an empty queue is placed in the first element of the array. which becomes both front and rear. Subsequent enqueues are placed at the array locations following rear i.e if the last element is stored at array location 11,the data for next enqueue is placed in element 12. 71
72
FIG-8 Physical structure
Queues using arrays Dequeue A dequeue takes place at the front of the queue. As an element is deleted from the queue, the queue front is advanced to the next location Fig-8 shows about physical structure of queue Queue ary front rare count Max size 7 17 5 11 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] ` FIG-8 Physical structure 72
73
QUEUE USING ARRAY Adding / enqueu function
1 if(rear==SIZE-1) 2 print queue is full / overflow 3 return; 4 else 5 rear++; 6 enter the element to ENQUEUE 7 if(front==-1) 8 front++; 73
74
QUEUE USING ARRAY Deleting /dequeue function 1. if(front==-1)
2. print queue is empty / underflow 3. return; 4. else 5. print the DEQUEUE element arr[front] 6. if(front==rear) 7. front=rear=-1 8. else 9. front++ 74
75
QUEUE USING ARRAY displayfunction 1.if(front==-1)
2. print queue is empty / underflow 3. return; 4. print the element in queue are 5. for(i=front;i<=rear;i++) 6. print arr[i] 75
76
Example -7 for queue using array
Queues using arrays Disavantages: In a queue, we delete elements at front and insert elements at rear. when rear reaches maximum size of an array, we can’t Insert new element though we have space at front end of a queue. Therefore queue is not full because there are empty elements at the beginning of the array. It shows queue is full. Fig shows array queue with last elements filled Queue rare Queue front [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] Fig array queue with last elements filled Example -7 for queue using array 76
77
Queues Linked List Enqueue
There two basic functions in queue using linked list 1) Enqueue 2) Dequeue Enqueue when we insert data into a queue, the queue’s front and rear pointers must be set to the new node When we insert data into a queue with data already in it, we must point both the link field in the last node and rear pointer to the new node. If insert is successful, it returns true else if no memory left for the new node, it returns false Fig shows enqueue 77
78
Queues Linked List Dequeue
If the queue is empty, we have underflow and return false We first ensure that the queue contains data. If the queue contains data, then set the front pointer to the next item in the queue If we dequeue the last item, the queue front pointer automatically becomes null pointer. it also assigns null pointer to link filed of the last node. Fig shows dequeue implementation. 78
79
Queues Linked List FIGURE -6 Enqueue Example 79
80
QUEUE USING LINKED LIST
struct node { int data; struct node*link; }; struct node*front=NULL,*rear=NULL; 80
81
QUEUE USING LINKED LIST
Enqueue function 1. struct node *temp 2. temp=(struct node*)malloc(sizeof(struct node)) 3. print enter the element to be inserted 4. temp->data=ele 5. temp->link=NULL 6. if(rear==NULL||front==NULL) 7. front=temp 8. else 9. rear->link=temp 10. rear=temp 81
82
QUEUE USING LINKED LIST
Dequeue function 1. struct node*temp; 2. if(front==NULL||rear==NULL) 3. print queue underflow 4. else 5. temp=front; 6. print deleted element temp->data 7. front=front->link 8. free(temp) 82
83
QUEUE USING LINKED LIST
Display function 1. struct node *temp 2.temp=front 3. if(front==NULL||rear==NULL) 4. print queue is empty 5. else 6. while(temp!=NULL) 7. print temp->data 8. temp=temp->link Example -6 for queue using linked list 83
84
Queues Linked List FIGURE -7 Dequeue Examples 84
85
Circular Queues This disadvantage is overcome by shifting all the elements from end to the beginning of the array In the above example, we shift from element 5 to 0 and 6 to 1 and so on. A more efficient alternative is found in circular queue In a circular queue, the last element is logically followed by the first element 85
86
Circular Queues Circular queue can be implemented in two ways
1.Circular queue using arrays 2.Circular queue using linked lists
87
Circular Queues [0] [1] [2] [3] [4] [5] Circular queue using arrays
Insertion into the circular queue [0] [1] [2] [3] [4] [5] Initially circular queue is empty front= -1 rear= -1
88
Circular Queues front=0 and rear=0 front=0 and rear=1
89
Circular Queues front=0 and rear=2 front=0 and rear=3
90
Circular Queues front=0 and rear=5 front=0 and rear=4
91
Circular Queues front=1 and rear=5 front=2 and rear=5
Circular queue using arrays Deletion from the circular queue front=1 and rear=5 front=2 and rear=5
92
Circular Queues front=3 and rear=5 Front=4 and rear=5
93
Circular Queues front=4 and rear=0 front=4 and rear=1
Circular queue using arrays Insertion from the circular queue front=4 and rear=0 front=4 and rear=1
94
Circular Queues front=4 and rear=2 front=4 and rear=3
95
Circular Queue Insert an element into a Circular Queue
if(front ==(rear+1)%MAXSIZE) printf("\n\nCIRCULAR QUEUE IS OVERFLOW"); else { if(front==-1) front=rear=0; else rear=(rear+1)%MAXSIZE; cqueue[rear]=item; } 95
96
Circular Queue Delete an element from a circular queue
if(front == -1) printf("\n\nCIRCULAR QUEUE IS UNDERFLOW"); else { a=cqueue[front]; if(front==rear) front=rear=-1; else front = (front+1)%MAXSIZE; printf("\n\nDELETED ELEMENT FROM QUEUE IS : %d ",a); } 96
97
Circular Queue Display the content of a circular queue
if(front == -1) printf("\n\nCIRCULAR QUEUE IS UNDERFLOW"); else { for(i=front;i<=rear;i++) { printf(“ %d \t“,cqueue[i]); } }
98
Circular Queue Insert an element into a Circular Queue using linked list void enqueue() { struct node*temp; temp=(struct node*)malloc(sizeof(struct node)); printf("\n enter the element to be inserted"); scanf("%d",&temp->data); temp->link=NULL; if(count==0) front=temp; else rear->link=temp; rear=temp; rear->link=front; count++; }
99
Circular Queue Delete an element from a circular queue void dequeue()
{ struct node*temp; if(front==NULL||rear==NULL) printf("\n queue underflow"); else { count--; if(front==rear) { printf("\n deleted element is %d",front->data); free(front); front=rear=NULL; } else { temp=front; printf("\n deleted element is %d\n",temp->data); front=front->link; rear->link=front; free(temp); } } }
100
Circular Queue Display the content of a circular queue void display()
{ int i; struct node*temp; if(front==NULL||rear==NULL) printf("\n queue is empty"); else if(count==0) temp=front; for(i=0;i<count;i++) printf("->%d",temp->data); temp=temp->link; } printf(")\n"); } } }
101
DEQUEUE A double-ended queue is an abstract data type similar to an simple queue, it allows you to insert and delete from both sides means items can be added or deleted from the front or rear end. 101
102
DEQUEUE A Deque or deck is a double-ended queue. Allows elements to be added or removed on either the ends.
103
DEQUEUE TYPES OF DEQUE Input restricted Deque Output restricted Deque
Elements can be inserted only at one end. Elements can be removed from both the ends. Output restricted Deque Elements can be removed only at one end. Elements can be inserted from both the ends.
104
DEQUEUE As STACK When insertion and deletion is made at the same side.
Deque as Stack and Queue As STACK When insertion and deletion is made at the same side. As Queue When items are inserted at one end and removed at the other end.
105
DEQUEUE Dequeue is also called as double ended queue and it allows user to perform insertion and deletion from the front and rear position. And it can be easily implemented using doubly linked list. On creating dequeue, we need to add two special nodes at the ends of the doubly linked list(head and tail). And these two nodes needs to be linked between each other(initially). head tail | | | ---| >| | | | | NULL | 0 | | | | 0 | NULL | | | | |< |--- | | | 105
106
DEQUEUE So, the header node goes before the first node of the queue and the trailer node goes after the last node in the queue. To do insertion at the front position, place the new node next to the head. And to do insertion at the rear position, place the new node before the tail. Similarly, dequeue operation can also be performed at the front and rear positions. Operations Insert a New Element From front Insert a New Element From rear Delete an Element From front Delete an Element From rear 106
107
DEQUEUE using Array 1. Algorithm for insertion at rear end:
Step 1: check if(front==-1) front++ rear++ read the element to insert a[rear] count++; Step 2: check if(rear>=SIZE-1) print Insertion is not possible, overflow!!! return Step 3: Increment the rear by 1 Step 4:stop 107
108
DEQUEUE using Array 2. Algorithm for insertion at front end:
Step 1: check if(front==-1) front++ rear++ read the element to insert a[rear] count++ Step 2: check if(rear>=SIZE-1) print Insertion is not possible, overflow!!! return Step 3: Repeat the steps a to d until i>0 a[i]=a[i-1] read the element to insert a[i] rear++; Step 4:stop 108
109
DEQUEUE using Array 3. Algorithm for deletion at rear end:
Step 1: check if (front==-1) Print Deletion is not possible: Dequeue is empty return Step 2: otherwise Print The deleted element is a[rear] Check if(front==rear) front=rear=-1 otherwise rear=rear-1 Step 3:stop 109
110
DEQUEUE using Array Algorithm for deletion at front end:
1: check if (front==-1) Print Deletion is not possible: Dequeue is empty return Step 2: otherwise Print The deleted element is a[front] Check if(front==rear) front=rear=-1 otherwise front=front-1 Step 3:stop 5.Algorithm for displaying the dequeue: Step 1: check if (front==-1) Print Dequeue is empty Repeat step a until i<=rear (i=front) Print a[i] 110
111
DEQUEUE using Linked list
ALGORITHM: Initialize the front and rear nodes with NULL values struct node *front=NULL,*rear=NULL,*cur,*temp 1. Algorithm for insertion at rear end: Step 1: Create a new node cur=(struct node*) malloc (sizeof (struct node)) Step 2: Read the content of node (cur->data) Step 3: Assign new node right link to NULL cur->right=NULL Step 4: Assign new node to front & rear node Check if(rear==NULL&&front==NULL) rear=front=cur Step 5: otherwise rear->right=cur cur->left=rear rear=cur Step 6:stop 111
112
DEQUEUE using Linked list
2. Algorithm for insertion at front end: Step 1: Create a new node cur=(struct node*) malloc (sizeof (struct node)) Step 2: Read the content of node (cur->data) Step 3: Assign new node right link to NULL cur->right=NULL Step 4: Assign new node to front & rear node Check if(rear==NULL&&front==NULL) rear=front=cur Step 5: otherwise cur->right=front front->left=cur front=cur Step 6:stop 112
113
DEQUEUE using Linked list
3. Algorithm for deletion at front end: Step 1: check if(front==NULL) Print deQueue is empty Step 2: otherwise Check if(front==rear) Print Deleted data is front->data front=rear=NULL Step 3: otherwise temp=front; print Deleted data is temp->data front=front->right front->left=NULL free(temp) Step 4: stop 113
114
DEQUEUE using Linked list
4. Algorithm for deletion at rear end: Step 1: check if(front==NULL) Print deQueue is empty Step 2: otherwise Check if(front==rear) Print Deleted data is rear->data front=rear=NULL Step 3: otherwise temp=rear; print Deleted data is temp->data if(front==rear) rear=rear->left rear->right=NULL free(temp) Step 4: stop 114
115
DEQUEUE using Linked list
5.Algorithm for displaying the dequeue: Step 1: check if(front==NULL) Print deQueue is empty Step 2: otherwise temp=front; repeat steps a-b until temp!= NULL a. printf("<-%d ->",temp->data) b. temp=temp->right; Step 3: stop 115
116
APPLICATIONS OF DEQUE Palindrome-checker
117
APPLICATIONS OF DEQUE 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.
118
OTHER APPLICATIONS OF DEQUE
Undo-Redo operations in Software applications.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.