Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars...

25
Data Structure Management(330701) 3.STACKS AND QUEUES 3.STACKS AND QUEUES Stack data structure: Stack data structure: A stack is a linear A stack is a linear OR OR non-primitive list in which insertion and deletion non-primitive list in which insertion and deletion operations are performed at only one end of the list. operations are performed at only one end of the list. A stack is A stack is Last in First out (LIFO) Last in First out (LIFO) Structure. Structure. A stack is a linear data structure in which elements are added and remove A stack is a linear data structure in which elements are added and remove from one end, called top of stack. from one end, called top of stack. For example of stack For example of stack is, consider a is, consider a stack of plates on the counter in stack of plates on the counter in cafeteria cafeteria, during the time of dinner, customer take plates from top of the , during the time of dinner, customer take plates from top of the stack and waiter puts the washed plates on the top of the stack. So new stack and waiter puts the washed plates on the top of the stack. So new plates are put on the top and old one yet bottom. plates are put on the top and old one yet bottom. Another example is Another example is Railway Shunting System. Railway Shunting System. Application of stack is Application of stack is Recursion, Stack Machine, Polish notation. Recursion, Stack Machine, Polish notation. 450 450 TOP TOP 100 100 300 300 230 230 124 124 BOTTOM BOTTOM Figure: Stack (vertical representation of stack) Figure: Stack (vertical representation of stack) The operations on the stack are represented by using vector consisting of The operations on the stack are represented by using vector consisting of number of elements. number of elements. The insertion operation is referred to as a PUSH The insertion operation is referred to as a PUSH operation and operation and deletion deletion operation is referred to as a POP operation operation is referred to as a POP operation. The most accessible element in the stack is known as a The most accessible element in the stack is known as a TOP TOP element and the element and the least accessible element in the stack is known as a least accessible element in the stack is known as a BOTTOM BOTTOM element. element. Since, the insertion and deletion operation are performed at only one end Since, the insertion and deletion operation are performed at only one end of the stack the element which is inserted last in the stack is first to of the stack the element which is inserted last in the stack is first to delete. So stack is also known as delete. So stack is also known as Last in First out Last in First out (LIFO) (LIFO). http://gtustudymaterial.blogspot.in/ 1

Transcript of Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars...

Page 1: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

3.STACKS AND QUEUES3.STACKS AND QUEUESStack data structure:Stack data structure:

A stack is a linear A stack is a linear OROR non-primitive list in which insertion and deletion operations are performed at only one non-primitive list in which insertion and deletion operations are performed at only one

end of the list.end of the list.

A stack is A stack is Last in First out (LIFO)Last in First out (LIFO) Structure. Structure.

A stack is a linear data structure in which elements are added and remove from one end, called top of stack.A stack is a linear data structure in which elements are added and remove from one end, called top of stack.

For example of stackFor example of stack is, consider a is, consider a stack of plates on the counter in cafeteriastack of plates on the counter in cafeteria, during the time of dinner,, during the time of dinner,

customer take plates from top of the stack and waiter puts the washed plates on the top of the stack. So newcustomer take plates from top of the stack and waiter puts the washed plates on the top of the stack. So new

plates are put on the top and old one yet bottom.plates are put on the top and old one yet bottom.

Another example isAnother example is Railway Shunting System. Railway Shunting System.

Application of stack isApplication of stack is Recursion, Stack Machine, Polish notation. Recursion, Stack Machine, Polish notation.

450 450 TOPTOP 100 100 300 300 230 230 124 124 BOTTOMBOTTOM

Figure: Stack (vertical representation of stack)Figure: Stack (vertical representation of stack)

The operations on the stack are represented by using vector consisting of number of elements.The operations on the stack are represented by using vector consisting of number of elements.

The insertion operation is referred to as a PUSHThe insertion operation is referred to as a PUSH operation and operation and deletion operation is referred to as a POPdeletion operation is referred to as a POP

operationoperation..

The most accessible element in the stack is known as a The most accessible element in the stack is known as a TOPTOP element and the least accessible element in the element and the least accessible element in the

stack is known as a stack is known as a BOTTOMBOTTOM element. element.

Since, the insertion and deletion operation are performed at only one end of the stack the element which isSince, the insertion and deletion operation are performed at only one end of the stack the element which is

inserted last in the stack is first to delete. So stack is also known as inserted last in the stack is first to delete. So stack is also known as Last in First outLast in First out (LIFO)(LIFO)..

Operations on Stack:Operations on Stack:(1)(1) PushPush: The operations that : The operations that add an element to the top of the stackadd an element to the top of the stack is called is called PUSHPUSH operation. It is used to operation. It is used to

insert an elementinsert an element into the stack. into the stack.

(2)(2) PopPop: The operation that : The operation that delete top element from the top of stackdelete top element from the top of stack is called is called POPPOP. it is used to delete an. it is used to delete an

element from stackelement from stack

(3)(3) Peep:Peep: it is used to it is used to retrieve iretrieve ithth element from the top of the stack. element from the top of the stack.

(4)(4) ChangeChange: it is used to : it is used to change value of the ichange value of the ithth element from the top of the stack. element from the top of the stack.

http://gtustudymaterial.blogspot.in/ 1

Page 2: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

Algorithms for Stack OperationAlgorithms for Stack Operation

(1) Algorithm for PUSH Operation.(1) Algorithm for PUSH Operation. In push operation, we can add elements to the top of the stack, so before push operation, user must In push operation, we can add elements to the top of the stack, so before push operation, user must

check the stack, it should not be a full.check the stack, it should not be a full. If stack is already full and when we try to add the elements then error occurs. It is called If stack is already full and when we try to add the elements then error occurs. It is called ““Stack Stack

Over FlowOver Flow” ” errorerror..

(2) Algorithm for POP Operation.(2) Algorithm for POP Operation.

In POP operation, we can delete or remove an elements from top of the stack, so before pop operation, In POP operation, we can delete or remove an elements from top of the stack, so before pop operation,

user must check the stack, stack should not be a empty.user must check the stack, stack should not be a empty.

If the stack is empty, and we try to pop an element, then error occur. It is called If the stack is empty, and we try to pop an element, then error occur. It is called ““Stack under FlowStack under Flow””

error.error.

http://gtustudymaterial.blogspot.in/

PUSH(S, TOP, VAL)PUSH(S, TOP, VAL)

This algorithm insert an element X to the top of the stack.This algorithm insert an element X to the top of the stack.

The Stack is represented by vector S which contains N elements.The Stack is represented by vector S which contains N elements.

TOP is a pointer which points to the top element of the Stack.TOP is a pointer which points to the top element of the Stack.

1.1. [Check for stack overflow][Check for stack overflow]

If TOP >= N thenIf TOP >= N then

Write (‘Stack Overflow’)Write (‘Stack Overflow’)

ReturnReturn

2.2. [Increment TOP][Increment TOP]

TOP = TOP + 1TOP = TOP + 1

3.3. [Insert Element][Insert Element]

S [TOP] = VALS [TOP] = VAL

4.4. [Finished][Finished]

ReturnReturn

POP(S, TOP)POP(S, TOP)

This algorithm removes an element from the Top of the Stack.This algorithm removes an element from the Top of the Stack.

The Stack is represented by vector S which contains N elements.The Stack is represented by vector S which contains N elements.

TOP is a pointer which points to the top element of the Stack.TOP is a pointer which points to the top element of the Stack.

1.1. [Check for the Underflow on the Stack][Check for the Underflow on the Stack]

If TOP = 0 thenIf TOP = 0 then

Write (‘STACK UNDERFLOW’)Write (‘STACK UNDERFLOW’)

ExitExit

2.2. [Decrement Pointer][Decrement Pointer]

TOP = TOP - 1 TOP = TOP - 1

3.3. [Return former top element of the stack][Return former top element of the stack]

Return(S [TOP + 1])Return(S [TOP + 1])

2

Page 3: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

(3) Algorithm for PEEP Operation. (3) Algorithm for PEEP Operation.

(4) Algorithm for CHANGE Operation.(4) Algorithm for CHANGE Operation.

Operation: Operation: PUSH 100(top=1)PUSH 100(top=1)

100100

TOPTOP

PUSH 200(top=2)PUSH 200(top=2)

200200100100

PUSH 300 (top=3)PUSH 300 (top=3)

300300200200100100

POP(top=2)POP(top=2)

200200100100

POP(top=1)POP(top=1)

100100

PUSH 1000(top=2)PUSH 1000(top=2)

10001000100100

http://gtustudymaterial.blogspot.in/

PEEP(S, TOP, I)PEEP(S, TOP, I)

This algorithm returns the value of the iThis algorithm returns the value of the ithth element from the Top of the Stack. element from the Top of the Stack.

The Stack is represented by vector S which contains N elements.The Stack is represented by vector S which contains N elements.

TOP is a pointer which points to the top element of the Stack.TOP is a pointer which points to the top element of the Stack.

1.1. [Check for the Underflow on the Stack][Check for the Underflow on the Stack]

If TOP – i + 1 ≤ 0 thenIf TOP – i + 1 ≤ 0 then

Write (‘STACK UNDERFLOW’)Write (‘STACK UNDERFLOW’)

ExitExit

2.2. [Assign the i[Assign the ithth element from the TOP of the Stack] element from the TOP of the Stack]

XX S [TOP – i+ 1] S [TOP – i+ 1]

3.3. [Return value][Return value]

Return (X)Return (X)

CHANGE(S, TOP, VAL, i)CHANGE(S, TOP, VAL, i)

This algorithm changes the value of the iThis algorithm changes the value of the ithth element from the Top of the Stack by element from the Top of the Stack by

X.X.

The Stack is represented by vector S which contains N elements.The Stack is represented by vector S which contains N elements.

TOP is a pointer which points to the top element of the Stack.TOP is a pointer which points to the top element of the Stack.

1.1. [Check for the Underflow on the Stack][Check for the Underflow on the Stack]

If TOP – i+ 1 ≤ 0 thenIf TOP – i+ 1 ≤ 0 then

Write (‘STACK UNDERFLOW’)Write (‘STACK UNDERFLOW’)

ExitExit

2.2. [Change i[Change ith th element from the TOP of the Stack] element from the TOP of the Stack]

S [TOP – i+ 1] S [TOP – i+ 1] VAL VAL

3.3. [finished][finished]

Return Return

3

Page 4: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

Application of StackApplication of StackThere are three main application of stack:There are three main application of stack:

(1) (1) Recursion:Recursion:RecursionRecursion means function call itself. means function call itself.

ItIt is the technique of defining a process in terms of itself.is the technique of defining a process in terms of itself.

Stack is widely used in recursion because of its Last in First out Property. Stack is widely used in recursion because of its Last in First out Property.

In terms of C language the function calling itself is known as recursion.In terms of C language the function calling itself is known as recursion.

There are two types of recursion:There are two types of recursion:

(1) Primitive Recursive function: Example Factorial Function(1) Primitive Recursive function: Example Factorial Function

(2) Non primitive Recursive function: Example Ackerman’s function (2) Non primitive Recursive function: Example Ackerman’s function (not in your syllabus).(not in your syllabus).

Primitive Recursive function:Primitive Recursive function:

Primitive Recursive function is known as recursively defined function.Primitive Recursive function is known as recursively defined function.

For Example For Example

The factorial function is defined as: The factorial function is defined as:

1 if N = 0 1 if N = 0

FACTORIAL (N) = FACTORIAL (N) =

N * FACTORIAL (N-1) otherwise N * FACTORIAL (N-1) otherwise

Non primitive Recursive function:Non primitive Recursive function:

Non primitive Recursive function is known as recursive use of the function.Non primitive Recursive function is known as recursive use of the function.

For Example For Example

The Ackerman’s function is defined as: The Ackerman’s function is defined as:

N + 1, if M = 0 N + 1, if M = 0 A (M, N) = A (M-1, 1), if N=0A (M, N) = A (M-1, 1), if N=0

A (M-1, A (M, N-1)), otherwise A (M-1, A (M, N-1)), otherwise

(2) (2) Evaluate polish notation:Evaluate polish notation:

There are basically three types of polish notation:There are basically three types of polish notation:

(A)(A) Infix (B) Prefix (C) PostfixInfix (B) Prefix (C) Postfix

When the operatorWhen the operator(+)(+) exists between two operands exists between two operands(A & B)(A & B) then it is known as Infix notation. then it is known as Infix notation.(e.g. A+B)(e.g. A+B)

When the operatorWhen the operator(+)(+) are written before their operands are written before their operands(A & B)(A & B) then it is known as Prefix notation then it is known as Prefix notation(Polish(Polish

notation)notation). . (e.g. +AB)(e.g. +AB)

When the operatorWhen the operator(+)(+) are written after their operands are written after their operands(A & B)(A & B) then it is known as Postfix notation then it is known as Postfix notation(Reverse(Reverse

polish notation)polish notation).. (e.g. AB+). (e.g. AB+).

Stack is widely used to convert infix notation into prefix or postfix notation.Stack is widely used to convert infix notation into prefix or postfix notation.

One of the major uses of stack is a polish notation or polish expression.One of the major uses of stack is a polish notation or polish expression.

http://gtustudymaterial.blogspot.in/ 4

Page 5: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

The process of writing the operators of an expression either before their operands or after operands areThe process of writing the operators of an expression either before their operands or after operands are

called the polish notation.called the polish notation.

Rules for converting infix notation to prefix/ postfixRules for converting infix notation to prefix/ postfix

1.1. The operations with heights precedence are converted first and then after a portion of the expression haveThe operations with heights precedence are converted first and then after a portion of the expression have

been converted to postfix.been converted to postfix.

2.2. It is to be treated as single operand.It is to be treated as single operand.

3.3. Take only two operands at a time to convert in a postfix from like A+BTake only two operands at a time to convert in a postfix from like A+B AB+ AB+

4.4. Always, convert the parenthesis firstAlways, convert the parenthesis first

5.5. Convert postfix exponentiation second if there are more than one exponentiation in sequence then takeConvert postfix exponentiation second if there are more than one exponentiation in sequence then take

order from right to left.order from right to left.

6.6. Convert in to postfix as multiplication and division operator, left to right.Convert in to postfix as multiplication and division operator, left to right.

7.7. Convert in postfix as addition and subtraction left to right.Convert in postfix as addition and subtraction left to right.

Example:Example:

Convert infix into POLISH notation (Prefix).Convert infix into POLISH notation (Prefix).

1.1. (A + B) * C(A + B) * C

= (+ A B) * C = (+ A B) * C

= * (+ A B) C = * (+ A B) C

= * + A B C = * + A B C

2.2. (A + B ) * (C + D)(A + B ) * (C + D)

= (+ A B) * (+ C D) = (+ A B) * (+ C D)

=*(+ A B) (+ C D) =*(+ A B) (+ C D)

=* + AB + CD =* + AB + CD

3.3. (A-B)+C*A+B(A-B)+C*A+B

=-AB+C*A+B=-AB+C*A+B

=-AB+*CA+B=-AB+*CA+B

=+-AB*CA+B=+-AB*CA+B

=++-AB*CAB=++-AB*CAB

4.4. (B*C/D)/(D/C+E)(B*C/D)/(D/C+E)=(*BC/D)/(D/C+E)=(*BC/D)/(D/C+E)=(/*BCD)/(D/C+E)=(/*BCD)/(D/C+E)=(/*BCD)/(/DC+E)=(/*BCD)/(/DC+E)=(/*BCD)/(+/DCE)=(/*BCD)/(+/DCE)=//*BCD+/DCE=//*BCD+/DCE

5.5. A*B/(C+D-E)A*B/(C+D-E)=A*B/(+CD-E)=A*B/(+CD-E)=A*B/(-+CDE)=A*B/(-+CDE)=*AB/-+CDE=*AB/-+CDE=/*AB-+CDE=/*AB-+CDE

Consider the following exampleConsider the following example

a + b / c –d * e where a=10, b=6, c=2, d=8, e=13 It is evaluated as followa + b / c –d * e where a=10, b=6, c=2, d=8, e=13 It is evaluated as follow

Step: 1 10 + Step: 1 10 + 6 / 26 / 2 – 8 * 13 – 8 * 13

Step: 2 10 + 3 – Step: 2 10 + 3 – 8 * 138 * 13

Step: 3 Step: 3 10 + 310 + 3 - 108 - 108

Step: 4 Step: 4 13 - 10413 - 104

Step: 5 - 91 Step: 5 - 91

http://gtustudymaterial.blogspot.in/ 5

Page 6: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

Example: converts following arithmetic expression into REVERSE POLISH notation (Postfix).Example: converts following arithmetic expression into REVERSE POLISH notation (Postfix).

1.1. A * B / C +DA * B / C +D= [AB*]/C+D= [AB*]/C+D= [AB*C/] +D= [AB*C/] +D=AB*C/D+=AB*C/D+

2.2. C*B*A/DC*B*A/D = [CB*]*A/D = [CB*]*A/D = [CB*A*]/D = [CB*A*]/D =CB*A*D/ =CB*A*D/

3.3. (A-B)+C*A+B(A-B)+C*A+B = [AB-] +C*A+B = [AB-] +C*A+B = [AB-] + [CA*] +B = [AB-] + [CA*] +B = [AB-CA*+] +B = [AB-CA*+] +B =AB-CA*+B+ =AB-CA*+B+

4.4. (B*C/D)/(D/C+E)(B*C/D)/(D/C+E)

= ([BC*]/D)/(DC/+E) = ([BC*]/D)/(DC/+E) = [BC*D/]/[DC/E+] = [BC*D/]/[DC/E+] =BC*D/DC/E+/ =BC*D/DC/E+/

5.5. A*B+C*D+E*FA*B+C*D+E*F =[AB*]+C*D+E*F =[AB*]+C*D+E*F =[AB*]+[CD*]+E*F =[AB*]+[CD*]+E*F

=[AB*]+[CD*]+[EF*] =[AB*]+[CD*]+[EF*]=[AB*CD*+]+[EF*]=[AB*CD*+]+[EF*]=AB*CD*+EF*+=AB*CD*+EF*+

6.6. A*B+A*(B*D+E*F)A*B+A*(B*D+E*F)=A*B+A*([BD*]+[EF*])=A*B+A*([BD*]+[EF*]) =A*B+A*([BD*EF*+]) =A*B+A*([BD*EF*+]) =[AB*]+A*[BD*EF*+]=[AB*]+A*[BD*EF*+]=[AB*]+[ABD*EF*+*] =[AB*]+[ABD*EF*+*] =AB*ABD*EF*+*+=AB*ABD*EF*+*+

7.7. A*B/(C+D-E)A*B/(C+D-E) =A*B/([CD+]-E) =A*B/([CD+]-E) =A*B/[CD+E-] =A*B/[CD+E-] =[AB*]/[CD+E-] =[AB*]/[CD+E-] =AB*CD+E-/ =AB*CD+E-/

8.8. A*A-B*BA*A-B*B =[AA*]-B*B =[AA*]-B*B =[AA*]-[BB*] =[AA*]-[BB*] =AA*BB*- =AA*BB*-

(3) (3) Stack Machine:

Stack Machines are also used to evaluate polish notations.

Two example of the stack machine are PDP-11 and B5000. These machines are well suited for stacking local

variables and parameter that arise in the function call.

Stack machines provides faster execution of polish notation.

IMPORTANT QUESTIONSIMPORTANT QUESTIONS(Asked question in the GTU Exam)(Asked question in the GTU Exam)

1. Discuss Stack characteristics and Write PUSH and POP algorithms.2. Write Infix, Prefix, Postfix notations with a suitable example. Also mention Operator precedence

associated with it.3. What is Stack? Explain Stack operations.4. Convert following expression into the postfix notation:

(i) a+b*(c/d)-e(ii) (a*b) * (c^(d+e)-f)

5. List application of stack? Explain any one in detail? Convert x*(c+d)+(j+k)*n+m*p into postfix expression.

6. Give trace of conversion process of following infix string to reverse polish expression. a+b*c-d/e*f.

7. (i) Convert following algebraic expression into reverse polish notation:(a) (a*b+c)+(d*e/b) (b) (a+(b*c-(m/n$p)*t)*s

http://gtustudymaterial.blogspot.in/ 6

Page 7: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

QueueQueue A queue is a linear list in which insertion is performed at one end called rear end and deletion is performed atA queue is a linear list in which insertion is performed at one end called rear end and deletion is performed at

another end of the list called front end.another end of the list called front end.

The information in such a list is proceeds in the same order as it was received.The information in such a list is proceeds in the same order as it was received.

Since insertion is performed at one end and deletion is performed at another end the element which is insertedSince insertion is performed at one end and deletion is performed at another end the element which is inserted

first is first to delete. So it is also known as first is first to delete. So it is also known as First in First out (FIFO)First in First out (FIFO) or or First Come First Serve (FCFS)First Come First Serve (FCFS) data data

structure.structure.

Examples of QueueExamples of Queue

(1)(1) A raw of students at registration counterA raw of students at registration counter

(2)(2) The bullet in a machine gun.(you cannot fire 2 bullets at the same time)

(3)(3) Line of cars waiting to proceeds in some direction at traffic signalLine of cars waiting to proceeds in some direction at traffic signal

Application of QueueApplication of Queue

A queue is the natural data structure for a system to serve its incoming requests. Most of the processA queue is the natural data structure for a system to serve its incoming requests. Most of the process

scheduling or disk scheduling algorithms in operating systems use queues. scheduling or disk scheduling algorithms in operating systems use queues.

Computer hardware like a processor or a network card also maintain buffers in the form of queues forComputer hardware like a processor or a network card also maintain buffers in the form of queues for

incoming resource requests. A stack-like data structure causes starvation of the first requests, and is notincoming resource requests. A stack-like data structure causes starvation of the first requests, and is not

applicable in such cases.applicable in such cases.

A mailbox or port to save messages to communicate between two users or processes in a system isA mailbox or port to save messages to communicate between two users or processes in a system is

essentially a queue-like structure.essentially a queue-like structure.

Queue is widely used in Simulation.Queue is widely used in Simulation.

http://gtustudymaterial.blogspot.in/ 7

Page 8: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

Algorithms for Queue operationsAlgorithms for Queue operations (1) Algorithm to insert an element in queue (1) Algorithm to insert an element in queue

(2) Algorithm to delete an element from the queue (2) Algorithm to delete an element from the queue

http://gtustudymaterial.blogspot.in/

QINSERT (Q, Front, Rear, N, Val)QINSERT (Q, Front, Rear, N, Val)

This function insert an element into the queueThis function insert an element into the queue

The Queue is represented by vector Q which contains N elements.The Queue is represented by vector Q which contains N elements.

Front is a pointer which points to the front endFront is a pointer which points to the front end

Rear is a pointer which points to the rear endRear is a pointer which points to the rear end

Y is the element to be inserted. Y is the element to be inserted.

1. [Overflow?]1. [Overflow?]

If Rear≥N thenIf Rear≥N then

Write (‘Queue Overflow’)Write (‘Queue Overflow’)

ExitExit

2. [Increment rear pointer]2. [Increment rear pointer]

RearRearRear+1Rear+1

3. [Insert element]3. [Insert element]

Q[Rear] Q[Rear] Val Val

4. [Is front pointer properly set?]4. [Is front pointer properly set?]

If Front=0 then If Front=0 then

Front Front11

ReturnReturn

5.5. [Finished][Finished]

Exit Exit

QDELETE (Q, Front, Rear)QDELETE (Q, Front, Rear)

The Queue is represented by vector Q which contains N elements.The Queue is represented by vector Q which contains N elements.

Front is a pointer which points to the front endFront is a pointer which points to the front end

Rear is a pointer which points to the rear endRear is a pointer which points to the rear end

1. [Underflow?]1. [Underflow?]

If Front = 0 thenIf Front = 0 then

Write (‘Queue Underflow’)Write (‘Queue Underflow’)

Exit Exit

2.2. [Delete element][Delete element]

XXQ [F]Q [F]

3.3. [Queue empty?][Queue empty?]

If Front =RearIf Front =Rear

Then FrontThen FrontRearRear00

Else FrontElse FrontFront+1 Front+1

4.4. [Return element][Return element]

Return (X) Return (X) 8

Page 9: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

Circular QueueCircular Queue A circular queue is a queue in which elements are arranged such that the first element in the queue follows theA circular queue is a queue in which elements are arranged such that the first element in the queue follows the

last element in the queue.last element in the queue.

The arrangement of circular queue is shown in figure below:The arrangement of circular queue is shown in figure below:

Here in the circular queue the first element q[0] follows the last element q[n-1].Here in the circular queue the first element q[0] follows the last element q[n-1].

Disadvantage of simple queueDisadvantage of simple queue is that even if we have a free memory space in a queue we cannot use that free is that even if we have a free memory space in a queue we cannot use that free

memory space to insert element.memory space to insert element.

For example consider following operations:For example consider following operations:

As shown in figure we insert three elements 5, 10, 15 in simple queue. After that we delete 5 and 10 as shownAs shown in figure we insert three elements 5, 10, 15 in simple queue. After that we delete 5 and 10 as shown

in figure. Now even we have a free memory space we cannot use that memory space. So simple queue resultsin figure. Now even we have a free memory space we cannot use that memory space. So simple queue results

in wastage of memory space. This problem can be solved by using circular queue.in wastage of memory space. This problem can be solved by using circular queue.

For example consider the following operations:For example consider the following operations:

http://gtustudymaterial.blogspot.in/ 9

Page 10: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

As shown in 1As shown in 1stst figure, we insert eight elements 10, 20,30,40,50,60,70,80 in simple queue. After that we delete figure, we insert eight elements 10, 20,30,40,50,60,70,80 in simple queue. After that we delete

10, 20 and 30 as shown in 210, 20 and 30 as shown in 2ndnd figure. Now we have a free memory space in circular queue and we can use that figure. Now we have a free memory space in circular queue and we can use that

memory space by incrementing rear pointer by 1(rear=0). memory space by incrementing rear pointer by 1(rear=0).

Algorithms for Circular queue OperationsAlgorithms for Circular queue Operations(1)(1) Algorithm to insert element in circular queue.Algorithm to insert element in circular queue.

http://gtustudymaterial.blogspot.in/

CQINSERT (Q, Front, Rear, N, Val)CQINSERT (Q, Front, Rear, N, Val)

This function inserts an element in to circular queue.This function inserts an element in to circular queue.

The Queue is represented by vector Q which contains N elements.The Queue is represented by vector Q which contains N elements.

Front is a pointer which points to the front endFront is a pointer which points to the front end

Rear is a pointer which points to the rear endRear is a pointer which points to the rear end

Val is the element to be inserted.Val is the element to be inserted.

1.1. [Reset rear pointer?][Reset rear pointer?]

If Rear = N-1 then If Rear = N-1 then

Rear Rear11

Else Else

Rear RearRear + 1Rear + 1

2.2. [Check Overflow][Check Overflow]

If Front=Rear then If Front=Rear then

Write (“Queue Overflow”) Write (“Queue Overflow”)

Exit Exit

3.3. [Insert element][Insert element]

Q[Rear] Q[Rear]ValVal

4.4. [Is front pointer properly set?][Is front pointer properly set?]

If Front = -1 then If Front = -1 then

Front Front00

Return Return10

Page 11: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

(2)(2) Algorithm to delete element from circular queue Algorithm to delete element from circular queue..

Priority QueuePriority Queue

A queue in which we are able to insert items or remove items from any position based on some priority isA queue in which we are able to insert items or remove items from any position based on some priority is

known as priority queue. known as priority queue.

R1R1 R2R2 ………… Ri-1Ri-1 O1O1 O2O2 …….……. Oj-1Oj-1 B1B1 B2B2 ………… Bk-1Bk-1

11 22 ………… 11 22 22 ……..…….. 22 33 33 ………… 33

http://gtustudymaterial.blogspot.in/

CQDELETE (Q, F, R)CQDELETE (Q, F, R)

This function deletes an element from circular queueThis function deletes an element from circular queue

The Queue is represented by vector Q which contains N elements.The Queue is represented by vector Q which contains N elements.

F is a pointer which points to the front endF is a pointer which points to the front end

R is a pointer which points to the rear endR is a pointer which points to the rear end

1.1. [Check Underflow error][Check Underflow error]

If Front = -1 then If Front = -1 then

Write (“Queue Underflow“) Write (“Queue Underflow“)

Exit Exit

2.2. [Delete element][Delete element]

X=Q[Front] X=Q[Front]

3.3. [Queue empty?][Queue empty?]

If Front = Rear or Front=N-1 then If Front = Rear or Front=N-1 then

Front FrontRearRear-1-1

Else Else

Front FrontFront+1Front+1

Return (X) Return (X)

4. [Finished] Exit

11

Page 12: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

Figure represents a priority queue of jobs waiting to use a computerFigure represents a priority queue of jobs waiting to use a computer

Priorities of 1, 2, 3 have been attached to jobs of real time, on-line and batch respectively.Priorities of 1, 2, 3 have been attached to jobs of real time, on-line and batch respectively.

Figure shows how the single priority queue can be visualized as three separate queues.Figure shows how the single priority queue can be visualized as three separate queues.

Priority 1:Priority 1:

Ri Ri

Oj Oj

Bk Bk

When elements are inserted, they are always added at the end of one of the queues as determined by theWhen elements are inserted, they are always added at the end of one of the queues as determined by the

priorities.priorities.

Elements in the second queue are deleted only when the first queue is empty.Elements in the second queue are deleted only when the first queue is empty.

Elements in the third queue are deleted only when the first and second queue are empty.Elements in the third queue are deleted only when the first and second queue are empty.

There are two types of priority queue(1)Ascending priority queue (2)Descending priority queue.There are two types of priority queue(1)Ascending priority queue (2)Descending priority queue.

Comparison of LIFO and FIFOComparison of LIFO and FIFOLIFOLIFO FIFOFIFO

(1) In LIFO the insertion and deletion(1) In LIFO the insertion and deletion

operation are performed at only one end.operation are performed at only one end.

(1) In FIFO the insertion and deletion operation are(1) In FIFO the insertion and deletion operation are

performed at two different ends.performed at two different ends.

(2) In LIFO the element which is inserted last(2) In LIFO the element which is inserted last

is first to delete.is first to delete.

(2) In FIFO the element which is inserted first is first(2) In FIFO the element which is inserted first is first

to delete.to delete.

(3) LIFO require only one pointer called TOP(3) LIFO require only one pointer called TOP (3) FIFO requires two pointers called front and rear.(3) FIFO requires two pointers called front and rear.

(4) Example: piles of trays in cafeteria (4) Example: piles of trays in cafeteria (4) Example: students at registration counter(4) Example: students at registration counter

(5) In LIFO there is no wastage of memory(5) In LIFO there is no wastage of memory

space.space.

(5) In FIFO even if we have free memory space(5) In FIFO even if we have free memory space

sometimes we cannot use that space to store elements.sometimes we cannot use that space to store elements.

Write a program to perform stack operation.Write a program to perform stack operation.#include<stdio.h>#include<stdio.h>

#include<conio.h>#include<conio.h>

#define N 5#define N 5

void main()void main()

{{

int s[N],val,op,i,top=-1;int s[N],val,op,i,top=-1;

http://gtustudymaterial.blogspot.in/ 12

R1R1 R2R2 ……………… Ri-1Ri-1 …..…..

O1O1 O2O2 ……………… Oj-1Oj-1 …..…..

B1B1 B2B2 ……………… Bk-1Bk-1 …..…..

Page 13: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

while(1)while(1)

{{

clrscr();clrscr();

printf("\nSTACK OPERATION \n");printf("\nSTACK OPERATION \n");

printf("\n1-PUSH \n2-POP \n3-PEEP \n4-CHANGE \n5-DISPLAY \n6-EXIT \n");printf("\n1-PUSH \n2-POP \n3-PEEP \n4-CHANGE \n5-DISPLAY \n6-EXIT \n");

printf("\nSELECT OPERATION :- ");printf("\nSELECT OPERATION :- ");

scanf("%d",&op);scanf("%d",&op);

switch(op)switch(op)

{{

case 1: case 1:

if(top>=N-1)if(top>=N-1)

{{

printf("\nSTACK OVERFLOW");printf("\nSTACK OVERFLOW");

}}

elseelse

{{

printf("ENTER VALUE TO PERFORM PUSH OPERATION :- ");printf("ENTER VALUE TO PERFORM PUSH OPERATION :- ");

scanf("%d",&val);scanf("%d",&val);

top++;top++;

s[top]=val;s[top]=val;

printf("VALUE INSERTED...");printf("VALUE INSERTED...");

}}

break;break;

case 2: case 2:

if(top<0)if(top<0)

{{

printf("\nSTACK UNDERFLOW");printf("\nSTACK UNDERFLOW");

}}

elseelse

{{

val=s[top];val=s[top];

top--;top--;

printf("\nPOPED ELEMENT :-%d",val);printf("\nPOPED ELEMENT :-%d",val);

}}

break;break;

case 3: case 3:

printf("\nENTER POSITION TO SHOW DATA :- ");printf("\nENTER POSITION TO SHOW DATA :- ");

scanf("%d",&i);scanf("%d",&i);

if(i>0)if(i>0)

{{

if((top-i+1)<0)if((top-i+1)<0)

{{

printf("\nSTACK UNDERFLOW");printf("\nSTACK UNDERFLOW");

}}

elseelse

http://gtustudymaterial.blogspot.in/ 13

Page 14: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

{{

val=s[top-i+1];val=s[top-i+1];

printf("\nDATA AT POSITION %d FROM TOP= %d",i,val);printf("\nDATA AT POSITION %d FROM TOP= %d",i,val);

}}

}}

elseelse

{{

printf("\nINVALID POSITION");printf("\nINVALID POSITION");

}}

break;break;

case 4: case 4:

printf("\nENTER POSTION TO CHANGE THE VALUE :- ");printf("\nENTER POSTION TO CHANGE THE VALUE :- ");

scanf("%d",&i);scanf("%d",&i);

if((top-i+1)<0)if((top-i+1)<0)

{{

printf("\nSTACK UNDERFLOW");printf("\nSTACK UNDERFLOW");

}}

elseelse

{{

printf("\nENTER NEW VALUE FOR %d POSITION :- ",i);printf("\nENTER NEW VALUE FOR %d POSITION :- ",i);

scanf("%d",&val);scanf("%d",&val);

s[top-i+1]=val;s[top-i+1]=val;

printf("VALUE CHANGED AT THE POSITION %d...",i);printf("VALUE CHANGED AT THE POSITION %d...",i);

}}

break;break;

case 5: case 5:

if(top==-1)if(top==-1)

{{

printf("\nSTACK IS EMPTY");printf("\nSTACK IS EMPTY");

}}

elseelse

{{

printf("\nNOW STACK IS :-\n");printf("\nNOW STACK IS :-\n");

printf("\n top->");printf("\n top->");

for(i=top;i>=0;i--)for(i=top;i>=0;i--)

{{

printf("%d\n",s[i]);printf("%d\n",s[i]);

printf("\t");printf("\t");

}}

}}

break;break;

case 6: case 6:

exit(0);exit(0);

break;break;

http://gtustudymaterial.blogspot.in/ 14

Page 15: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

default: default:

printf("\nINVALID CHOICE FOR OPERATION");printf("\nINVALID CHOICE FOR OPERATION");

break;break;

}}

getch();getch();

}}

}}

Write a program to perform Queue Operation.Write a program to perform Queue Operation.

#include<stdio.h>#include<stdio.h>

#include<conio.h>#include<conio.h>

#define N 5#define N 5

void main()void main()

{{

int q[N],val,op,i,front=-1,rear=-1;int q[N],val,op,i,front=-1,rear=-1;

while(1)while(1)

{{

clrscr();clrscr();

printf("\nSTACK OPERATION \n");printf("\nSTACK OPERATION \n");

printf("\n1-PUSH \n2-POP \n3-DISPLAY \n4-EXIT \n");printf("\n1-PUSH \n2-POP \n3-DISPLAY \n4-EXIT \n");

printf("\nSELECT OPERATION :- ");printf("\nSELECT OPERATION :- ");

scanf("%d",&op);scanf("%d",&op);

switch(op)switch(op)

{{

case 1: case 1:

if(rear==N-1)if(rear==N-1)

{{

printf("\nQUEUE OVERFLOW");printf("\nQUEUE OVERFLOW");

}}

elseelse

{{

printf("ENTER VALUE TO PERFORM PUSH OPERATION :- ");printf("ENTER VALUE TO PERFORM PUSH OPERATION :- ");

scanf("%d",&val);scanf("%d",&val);

rear++;rear++;

q[rear]=val;q[rear]=val;

printf("VALUE INSERTED...");printf("VALUE INSERTED...");

if(front==-1)if(front==-1)

front=0;front=0;

}}

break;break;

case 2: case 2:

if(front<0)if(front<0)

{{

printf("\nQUEUE UNDERFLOW");printf("\nQUEUE UNDERFLOW");

}}

elseelse

http://gtustudymaterial.blogspot.in/ 15

Page 16: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

{{

val=q[front];val=q[front];

if(front==rear)if(front==rear)

{{

front=-1;front=-1;

rear=-1;rear=-1;

}}

elseelse

{{

front++;front++;

}}

printf("\nPOPED ELEMENT :-%d",val);printf("\nPOPED ELEMENT :-%d",val);

}}

break;break;

case 3: case 3:

if(front==-1)if(front==-1)

{{

printf("\nQUEUE IS EMPTY");printf("\nQUEUE IS EMPTY");

}}

elseelse

{{

printf("\nNOW QUEUE IS :-\n");printf("\nNOW QUEUE IS :-\n");

printf("\n front->");printf("\n front->");

for(i=front;i<=rear;i++)for(i=front;i<=rear;i++)

{{

printf("%d\n",q[i]);printf("%d\n",q[i]);

printf("\t");printf("\t");

}}

}}

break;break;

case 4: case 4:

exit(0);exit(0);

break;break;

default: default:

printf("\nINVALID CHOICE FOR OPERATION");printf("\nINVALID CHOICE FOR OPERATION");

break;break;

}}

getch();getch();

}}

}}

Write a program to perform Circular queue operation.Write a program to perform Circular queue operation.

#include<stdio.h>#include<stdio.h>http://gtustudymaterial.blogspot.in/ 16

Page 17: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

#include<conio.h>#include<conio.h>

#define N 5#define N 5

void main()void main()

{{

int q[N],val,op,i,j,k,front=-1,rear=-1;int q[N],val,op,i,j,k,front=-1,rear=-1;

while(1)while(1)

{{

clrscr();clrscr();

printf("\nSTACK OPERATION \n");printf("\nSTACK OPERATION \n");

printf("\n1-PUSH \n2-POP \n3-DISPLAY \n4-EXIT \n");printf("\n1-PUSH \n2-POP \n3-DISPLAY \n4-EXIT \n");

printf("\nSELECT OPERATION :- ");printf("\nSELECT OPERATION :- ");

scanf("%d",&op);scanf("%d",&op);

switch(op)switch(op)

{{

case 1: case 1:

printf("ENTER VALUE TO PERFORM PUSH OPERATION :- ");printf("ENTER VALUE TO PERFORM PUSH OPERATION :- ");

scanf("%d",&val);scanf("%d",&val);

if(rear>=N-1)if(rear>=N-1)

{{

rear=0;rear=0;

}}

elseelse

{{

rear++;rear++;

}}

if(rear==front)if(rear==front)

{{

if(rear==0)if(rear==0)

rear=N-1;rear=N-1;

elseelse

{{

rear--;rear--;

}}

printf("\nQUEUE OVERFLOW");printf("\nQUEUE OVERFLOW");

break;break;

}}

q[rear]=val;q[rear]=val;

printf("VALUE INSERTED...");printf("VALUE INSERTED...");

if(front==-1)if(front==-1)

front=0;front=0;

break;break;

case 2: case 2:

http://gtustudymaterial.blogspot.in/ 17

Page 18: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

if(front==-1)if(front==-1)

{{

printf("\nQUEUE UNDERFLOW");printf("\nQUEUE UNDERFLOW");

}}

elseelse

{{

val=q[front];val=q[front];

if(front==rear||front==N-1)if(front==rear||front==N-1)

{{

front=-1;front=-1;

rear=-1;rear=-1;

}}

elseelse

{{

front++;front++;

}}

printf("\nPOPED ELEMENT :-%d",val);printf("\nPOPED ELEMENT :-%d",val);

}}

break;break;

case 3: case 3:

printf("front=%d rear=%d",front,rear);printf("front=%d rear=%d",front,rear);

if(front==-1)if(front==-1)

{{

printf("\nQUEUE IS EMPTY");printf("\nQUEUE IS EMPTY");

}}

elseelse

{{

printf("\nNOW QUEUE IS :-\n");printf("\nNOW QUEUE IS :-\n");

printf("\n front->");printf("\n front->");

if(front>rear)if(front>rear)

{{

for(j=0;j<=rear;j++)for(j=0;j<=rear;j++)

{{

printf("%d\n",q[j]);printf("%d\n",q[j]);

printf("\t");printf("\t");

}}

for(k=front;k<=N-1;k++)for(k=front;k<=N-1;k++)

{{

printf("%d\n",q[k]);printf("%d\n",q[k]);

printf("\t");printf("\t");

}}

http://gtustudymaterial.blogspot.in/ 18

Page 19: Web viewThe bullet in a machine gun.(you cannot fire 2 bullets at the same time) Line of cars waiting to proceeds in some direction at traffic signal. Application. of Queue

Data Structure Management(330701)

}}

elseelse

{{

for(i=front;i<=rear;i++)for(i=front;i<=rear;i++)

{{

printf("%d\n",q[i]);printf("%d\n",q[i]);

printf("\t");printf("\t");

}}

}}

}break; }break;

case 4: case 4:

exit(0);exit(0);

break;break;

default: default:

printf("\nINVALID CHOICE FOR OPERATION");printf("\nINVALID CHOICE FOR OPERATION");

break;break;

}}

getch();getch();

} }} }

IMPORTANT QUESTIONSIMPORTANT QUESTIONS(Asked question in the GTU Exam)(Asked question in the GTU Exam)

1) What is Queue? Explain disadvantages of simple queue.2) Explain Queue fundamentals with Queue Insertion & deletion algorithms.3) What is Circular queue? Compare circular queue with normal queue.4) Write and explain algorithm to insert(PUSH) & delete(POP) element in circular queue.

ORUsing array data structure, write an algorithm to insert & delete a data item from the circular queue.

Inspirational Quote:Inspirational Quote:

The secret of success is to know something nobody else knows.

http://gtustudymaterial.blogspot.in/ 19