data structures(r16) unit- ii 2.1 stac kstmarysguntur.com/cse materials/ds/unit_ii.pdflike a rray a...

16
Data Structures(R16) UNIT- II 2.1 STAC K Stac k is a linea r data structure and very muc h useful in various a pplic ations of c omputer sc ienc e. De finition A stac k is an orde red c ollec tion of homoge neous data ele ments, where the insertion and deletion ope ration takes plac e at one end only, c alled the top of the stac k. Like a rray a nd linke d list, stac k is also a linear data structure, but the only differenc e is that in c ase of forme r two, insertion and de letion ope rations c an take plac e at any position. In a stac k the last inse rted ele ment is a lways proc essed first. Acc ordingly, stac ks are c alle d as Last-in-First-out (LIFO) lists. Other na mes used for stac ks are “piles” and “push-down lists”. Stac k is most c ommonly used to store loc al variables, pa ra meters a nd return a ddresses whe n a function is c alled. Stac k Model of Stac k The above figure is a pic torial re prese ntation of a stac k. N=5 is the maximu m c apac ity of the stac k. Currently there are three e le me nts in the stac k, so the variable top value is 3.The varia ble top always keeps trac k of the top most ele me nt or position. STAC K OPE RATIONS 1. PUSH: Push” is the term used to insert an ele ment into a stac k. 2. POP: Pop” is the term used to delete an ele ment from a stac k. Two additiona l terms used with stac ks are “overf low” & “unde rflow”. Ov erf low oc c urs when we try to push more information on a stac k that it c an hold. Unde rflow oc c urs when we try to pop an ite m from a stac k whic h is e mpty. 2.2 RE PRE SE NTATION OF STAC KS A stac k may be represented in the me mory in va rious ways. Mainly there a re two ways. They are: 1. Using one dimens iona l a rrays(Static Imple mentation) 2. Using linke d lists(Dy na mic Imple me ntation) 2.2.1 Representation of Stack using Array First we have to alloc ate a me mory bloc k of s uffic ient size to acc ommodate the full c apac ity of the stac k. Then, starting from the first loc ation of the me mory bloc k, ite ms of the stac k c an be stored in seque ntial fashion.

Upload: others

Post on 17-Mar-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

2.1 STAC K

Stac k is a linea r data structure and very muc h useful in various a pplic ations of c omputer

sc ienc e.

De finition

A stac k is an orde red c ollec tion of homoge neous data ele ments, where the insertion and

deletion ope ration takes plac e at one end only, c alled the top of the stac k.

Like a rray a nd linke d list, stac k is also a linear data structure, but the only differenc e is that in

c ase of forme r two, insertion and de letion ope rations c an take plac e at any position.

In a stac k the last inse rted ele ment is a lways proc essed first. Acc ordingly, stac ks are c alle d as

Last-in-First-out (LIFO) lists. Other na mes used for stac ks are “piles” and “push-down

lists”.

Stac k is most c ommonly used to store loc al variables, pa ra meters a nd return a ddresses whe n

a function is c alled.

Stac k Model of Stac k

The above figure is a pic torial re prese ntation of a stac k. N=5 is the maximu m c apac ity of the

stac k. Currently there are three e le me nts in the stac k, so the variable top value is 3.The

varia ble top always keeps trac k of the top most ele me nt or position.

STAC K OPE RATIONS

1. PUSH: “Push” is the term used to insert an ele ment into a stac k.

2. POP: “Pop” is the term used to delete an ele ment from a stac k.

Two additiona l terms used with stac ks are “overf low” & “unde rflow”. Ov erf low oc c urs when we

try to push more information on a stac k that it c an hold. Unde rflow oc c urs when we try to pop

an ite m from a stac k whic h is e mpty.

2.2 RE PRE SE NTATION OF STAC KS

A stac k may be represented in the me mory in va rious ways. Mainly there a re two ways. They

are:

1. Using one dimens iona l a rrays(Static Imple mentation)

2. Using linke d lists(Dy na mic Imple me ntation)

2.2.1 Representation of Stack using Array

First we have to alloc ate a me mory bloc k of s uffic ient size to acc ommodate the full c apac ity of

the stac k. Then, starting from the first loc ation of the me mory bloc k, ite ms of the stac k c an be

stored in seque ntial fashion.

Page 2: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

In the figure Itemi denotes the ith item in the stac k; l & u

denote the inde x ra nge of array in use; us ually these values

are 1 and s ize respec tively. Top is a pointer to point the

position of a rray upto whic h it is filled with the ite ms of stac k.

With this representation following two statuses c an be stated:

EMPTY: Top<l

FULL: Top>=u +l-1

Algorithms for Stac k Ope rations

Algorithm PUSH (STAC K, TOP, MAXSTK, ITEM)

This algorithm pushes an ITEM onto a stac k.

Step 1: If TOP = MAXST K, then: \\ Chec k Overflow?

Print: OVERFLOW, and Exit.

Step 2: Set TOP := TOP + 1. \\ inc reases TOP by 1 Step 3: Set STACK[TOP] := ITEM. \\ Inserts ITEM in new TOP position. Step 4: Exit.

He re we have assume d that array inde x va ries from 1 to SIZE and Top points the loc ation of

the c urre nt top most ite m in the stac k.

Algorithm POP (STAC K, TOP, ITE M)

This algorithm de letes the top ele ment of STACK and assigns it to the variable ITEM.

Step 1: If TOP = NULL, then: \\ Chec k Underf low.

Print: UNDERFLOW, and Exit.

Step 2: Set ITEM := STACK[TOP]. \\ Assigns TOP ele ment to ITEM.

Step 3: Set TOP := TOP – 1. \\ Dec reases TOP by 1.

Step 4: Exit.

/* C implementation of Stac k using Arrays */

#inc lude <stdio.h>

#inc lude <c onio. h>

#inc lude <stdlib. h>

#def ine size 5

struc t stac k

{

} st;

int s[size];

int top;

int isfull() {

if (st.top >= s ize - 1)

return 1;

else

return 0;

}

void pus h(int ite m) {

Page 3: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

st.top++;

st.s[st.top] = ite m;

}

int ise mpty() {

if (st.top == -1)

return 1;

else

return 0;

}

int pop() {

int item;

item = st.s[st.top];

st.top--;

return (ite m);

}

printf("\nMa in Me nu");

printf("\n1.P ush \n2.Pop \n3. Dis play

\n4.e xit ");

printf("\nEnter your c hoic e:");

sc anf("%d", &c hoic e);

switc h (c hoic e) {

c ase 1:

printf("\ nEnter the ite m to be

pushed:");

sc anf("%d", &ite m);

if (isfull())

printf("\nStac k is Full!");

else

push(ite m);

break;

c ase 2:

if (ise mpty())

printf( "\nEmpty stac k…! Unde rflow

void display() {

int i;

if (ise mpty())

printf("\nStac k Is Empty!");

else {

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

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

!!");

ite m);

else {

item = pop();

printf("\nThe popped ele me nt is %d",

}

break;

} c ase 3:

} display();

break;

int ma in() {

int item, c hoic e;

c har ans;

st.top = -1;

c lrsc r();

printf("\nImple me ntation Of Stac k");

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

do {

c ase 4:

exit(0);

}

printf("\nDo you want to c ontinue?");

ans = getc he();

} while (ans == 'Y' || ans == 'y ');

return 0;

}

2.2.2 Linked representation of Stacks

The linke d re presentation of a stac k, c ommonly termed linked stac k is a stac k that is

imple me nted using a singly linked list. The INFO f ields of the nodes hold the ele ments of the

stac k and the LINK fie lds hold pointers to the neighboring ele ment in the stac k. The START

pointer of the linked list behaves as the TOP pointer va riable of the stac k and the null pointer

of the last node in the list signals the bottom of the stac k.

Page 4: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

Algorithms for Stac k Ope rations

Algorithm : PUSH _LINKSTAC K(INFO, LINK, TOP, AVAIL, ITE M).

This algorithm pushes an ITEM into a linke d stac k.

Step 1: If AVAIL = NULL, then: \\ Chec k Overflow?

Write: OVERFLOW, and Exit.

Step 2: [Take node from AVAIL list.]

Set NEW := AVAIL, and AVAIL := LINK[AVAIL].

Step 3: [Copies ITEM into new node.]

Set INFO[NEW] := ITEM.

Step 4: [Add this node to the STACK.]

Set LINK[NEW] := TOP, and TOP := NEW.

Step 5: Exit.

Algorithm : POP_LINKSTAC K(INF O, LINK, TOP, AVAIL, ITE M).

This algorithm de letes the top ele ment of a linked stac k and assigns it to the variable ITEM.

Step 1: If TOP = NULL, then: \\ Chec k Underf low?

Write: UNDERFLOW and Exit.

Step 2: Set ITEM := STACK[TOP]. \\ Copies the TOP ele ment of STACK into ITEM.

Step 3: Set TEMP := TOP, and

TOP := LINK[TOP]. \\ Reset the position of TOP.

Step 4: [Add node to the AVAIL list.]

Set LINK[TEMP] := AVAIL, AVAIL := TEMP.

Step 5: Exit.

2.3 APPLICATIONS OF S TAC KS

1. Reve rsing ele me nts in a list or string.

2. Rec urs ion Imple mentation.

3. Me mory manage me nt in operating syste ms.

4. Evaluation of postfix or prefix e xpressions.

5. Infix to postfix express ion c onvers ion.

6. Tree and Graph t raversa ls.

7. Chec king for pa renthesis ba la nc ing in arithmetic expressions.

8. Used in pars ing.

2.4 Stac k as ADT

The Stac k ADT imple mentation in C is quite simple. Instead of storing data in eac h node, we

store pointer to the data.

ADT implementation of Stacks

The node structure c onsists only of a data pointer and link pointer. The Stac k head structure

also c ontains only two ele me nts – a pointer to the top of the stac k and a c ount of the number

of entries in the stac k

Page 5: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

2.5 Arithmetic Express ions

An express ion is a c ollec tion of operators and ope rands that represents a spec ific value. In

above definition,

Operator is a sy mbol (+,-, >, <,..) whic h performs a pa rtic ular task like a rithmetic or

logic al or re lationa l ope ration etc .,

Opera nds are the values on whic h the operators c an perform the task.

Expression Ty pes

Based on the operator position, express ions a re div ided into THREE types. They are as follows :

1. Infix Express ion

2. Postfix Expression

3. Prefix Expression

Infix Express ion

In infix e xpression, operator is used in between operands. This notation is also c alled as

polish notation. The gene ral struc ture of an Infix e xpression is:

<Opera nd1> <Ope rator> <Ope rand2> Ex : A + B

Postfix Expression

In postfix express ion, ope rator is used after operands. We c an say that "Operator follows the

Opera nds ". This notation is a lso c alled as reverse - polish no tation. The genera l struc ture of

Postfix express ion is:

<Opera nd1> <Ope rand2> <Ope rator> Ex : A B +

Pre fix Expression

In prefix express ion, operator is used before ope rands. We c an say that "Ope rands follows the

Operator". The general struc ture of Prefix express ion is:

<Operator><Ope rand1> <Ope rand2> Ex : + A B

In 2nd and 3rdnotations, parentheses are not needed to determine the order eva luation of the

operations in any a rithmetic express ion.

Eg.: Infix Pre fix Postfix

1. A+B*C A+{*BC}

+A* BC A+{BC*}

ABC* +

{ } indic ate partial trans lation

2. (A+B)*C {+AB}*C {AB+}*C

*+ABC AB+C* The c omputer usually evaluates an arithmetic expression written in inf ix notation in two steps.

1. It c onverts the expression to postfix notation and

2. It evaluates the postfix express ion.

In eac h step, the stac k is the main tool that is used to acc omplish the give n task.

2.5.1 Tra nsform ing Infix Expression into Postfix Expression

In the inf ix e xpression we assume only e xponentiation(^ or **), multiplic ation(*), division(/),

addition(+), subtrac tion(-) operations. In addition to the above operators and operands they

may c ontain left or right parenthes is. The operators three levels of priorities a re:

Page 6: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

Priority Operators HIGHEST ^ or ** NEXT HIGHEST * , / LOW EST + , –

The follow ing a lgorithm tra nsforms the infi x express ion Q into the equiva lent postfix

expression P. The algorithm uses a stac k to tempora rily ho ld ope rators and left parenthesis.

ALGORITH M INF IX-TO-POSTF IX (Q)

Step1: Push „(„ onto stac k and add „)‟ to the end of Q.

Step 2: Sc an Q from left to right and repeat steps 3 to 6 for eac h ele ment of Q until STACK is

e mpty.

Step 3: If an operand is enc ountered, add it to P.

Step 4: If a left parentheses is enc ountered, pus h it onto STACK.

Step 5: If an operator Ө is enc ountered, then:

a) Repeatedly po p from STACK and add to P eac h operator (on the top of

STACK) whic h has the same prec edenc e as or highe r prec edenc e than Ө.

b) Add Ө to the STACK

[End of If Structure]

Step 6: If a right pare ntheses is enc ountered, then:

a) Repeatedly pop from STACK and add to P eac h operator (on the top of

STACK) until a left parentheses is enc ountered.

b) Re move the left parenthesis. [Do not add this to P]

Step 7: Exit.

EXAMPLE 1: Cons ide r the follow ing inf ix e xpress ion Q: A + ( B * C - (D / E ^ F) * G) * H

Symbol Sca nned Stack Conte nts Expression P

Initial (

(1) A ( A

(2) + ( + A

(3) ( ( + ( A

(4) B ( + ( AB

(5) * ( + ( * AB

(6) C ( + ( * ABC

(7) - ( + ( - ABC *

(8) ( ( + ( - ( ABC*

(9) D ( + ( - ( ABC*D

(10) / ( + ( - ( / ABC*D

(11) E ( + ( - ( / ABC*DE

(12) ^ ( + ( - ( / ^ ABC*DE

(13) F ( + ( - ( / ^ ABC*DE

Page 7: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

(14) ) ( + ( - ABC*DE^/

(15) * ( + ( - * ABC*DE^/

(16) G ( + ( - * ABC*DE^/G

(17) ) ( + ABC*DE^/G*-

(18) * ( + * ABC*DE^/G*-

(19) H ( + * ABC*DE^/G*-H

(20) ) ABC*DE^/G*-H * +

OUTPUT P: ABC*DE ̂ /G*-H * + (POSTF IX FORM)

EXAMPLE 2: Cons ide r the infix e xpression Q: (A+B)*C + (D- E)/F)

Symbol Sca nned Stack Conte nts Expression P

Initial (

(1) ( ((

(2) A (( A

(3) + ((+ A

(4) B ((+ AB

(5) ) ( AB+

(6) * (* AB+

(7) C (* AB+C

(8) + (+ AB+C*

(9) ( (+( AB+C*

(10) D (+( AB+C* D

(11) - (+(- AB+C* D

(12) E (+(- AB+C* DE

(13) ) (+ AB+C* DE-

(14) / (+/ AB+C* DE-

(15) F (+/ AB+C* DE-F

(16) ) AB+C* DE-F/+

OUTPUT P: AB+C* DE-F/+ (POSTFIX FORM)

2.5.2 EVALUATION OF A POSTF IX EXPRE SSION

Suppose P is a n arithmetic express ion w ritten in postfix . The following a lgorithm uses a

STACK to hold ope rands during the evaluation of P.

Algorithm EVALPOSTF IX(p)

Step 1: Add a right pare ntheses „)‟ at the end of P. //this acts as a sentinel

Step 2: Sc an P from left to right and repeat steps 3 and 4 for eac h ele ment of P until the

sentinel „)‟ is enc ountered.

Step 3: If an operand is enc ountered, push on STACK.

Step 4: If an operator Ө is enc ountered, then:

Page 8: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

a) Re move the two top eleme nts of STACK, where A is the top ele ment and B is

the next- to-top ele ment.

b) Evaluate B Ө A.

c ) Push the result of (b) bac k on STACK

[End of If structure]

[End of step2 loop]

Step 5: Set VALUE equal to top ele ment on STACK.

Step6: Return(VALUE)

Step 7: Exit.

EXAMPLE: Cons ide r the follow ing postfix e xpression:

P: 5, 6, 2, +, *, 12, 4, /, -

Sy mbols Sc anned STACK (1) 5 5 (2) 6 5, 6 (3) 2 5, 6, 2 (4) + 5, 8 (5) * 40 (6) 12 40, 12 (7) 4 40, 12, 4 (8) / 40, 3 (9) - 37 (10) )

The result of this postfix expression is 37.

2.6 QUEUES

Queue is a linear data struc ture used in va rious applic ations of c omputer sc ienc e. Like

people stand in a queue to get a partic ular serv ic e, various proc esses will wait in a que ue for

their turn to avail a servic e.

Queue is a linea r list in w hic h inse rtions takes plac e at one end c alled

the rear or tail of the queue and de letions at the other end c alle d as front or

head of the queue.

When an e le ment is to join the que ue, it is inserted at the rear end of

the queue and w hen an e le ment is to be deleted, the one at the front end of

the queue is deleted automatic ally.

In queues a lways the first inse rted ele ment will be the first to be deleted. That‟s why it

is also c alled as FIFO – First-in F irst-Out data structure (or FCFS – F irst Come First Serve data

struc ture).

APPLIC ATIONS of QUE UE

CPU Sc heduling (Round Robin Algorithm)

Printer Spooling

Tree & Graph Traversals

Palindrome Chec ke r

Undo & Redo Operations in some Software‟s

OPE RATIONS ON QUEUE

The queue data structure supports two operations:

Page 9: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

Enque ue: Inserting an ele me nt into the queue is c alled enqueuing the que ue. After the data

have been inse rted into the queue, the new ele me nt bec omes the rear.

Dequeue: De leting a n ele ment from the queue is c alled de queuing the queue. The data at the

front of the queue are returne d to the user and re move d from the queue.

TY PES OF QUE UES

1. Simple or Single Ended Que ue: In this queue inse rtions ta ke plac e at one end and

deletions take plac e at other end.

2. Circular Queue: It is s imila r to single ended queue, but the front is c onnec ted bac k to

rear. He re the me mory c an be utilized effectively.

3. Double Ende d Queue: In double e nded queue both the insertions and de letions c an

take plac e at both the ends.

4. Priority Queue: In priority que ue the ele me nts are not deleted ac c ording to the orde r

they entered into the queue, but acc ording to the priorities assoc iated with the

ele me nts.

2.6.1 IMPLE ME NTATION OF QUE UES

Queues c an be imple me nted or re presented in me mory in two ways:

1. Using Arrays (Static Imple me ntation).

2. Using Linked Lists (Dy na mic Imple mentation).

2.6.1.1 Im pleme ntation of Queue Us ing Arrays

A c ommon method of imple me nting a queue data structure is to use another sequentia l

data struc ture, viz, arrays. With this representation, two pointers na me ly, Front and Rear a re

used to indic ate two ends of the queue. For insertion of ne xt ele me nt, pointer Rea r will be

adjusted and for de letion pointer Front will be adjusted.

Howeve r, the array imple mentation puts a limitation on the c apac ity of the queue. The

numbe r of ele me nts in the queue c annot e xc eed the ma ximu m dimens ion of the one

dimens iona l array. Thus a que ue that is acc ommodated in an a rray Q[1:n], c annot hold more

than n ele me nts. Henc e every insertion of an e le ment into the queue has to nec essarily test

for a QUEUE FULL c ondition before exec uting the insertion ope ration. Aga in, eac h de letion has

to ensure that it is not attempted on a queue w hic h is already e mpty c alling for the need to

test for a QUEUE EMPTY c ondition before exec uting the deletion operation.

Algorithm of inse rt operation on a queue

Proc edure INSERTQ (Q, n, ITEM, REAR)

// this proc edure inse rts an ele me nt ITEM into Queue with c apac ity n

Step 1: if(REAR=n ) then

Write:“QUEUE_FULL” a nd Exit

Step 2: REAR=REAR + 1 //Inc re ment REAR

Step 3: Q[REAR]= ITEM //Inse rt ITEM as the rear ele me nt

Step 4: Exit

It c an be obse rved that addition of eve ry new ele me nt int o the queue inc re me nts the REAR

varia ble. However, before inse rtion, the c ondition whether the que ue is full is c hec ked.

Algor ithm of delete operation on a queue

Proc edure DELETEQ (Q, FRONT, REAR, ITEM)

Step 1: If (FRONT >REAR) then:

Write: “QUEUE EMPTY ” and Exit.

Step 2: ITEM = Q[F RONT]

Page 10: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

Step 3: FRONT =F RONT + 1

Step 4: Exit.

To perform de lete operation, the partic ipation of both the variables F RONT and REAR is

essential. Before deletion, the c ondition F RONT =REAR c hec ks for the e mptiness of the que ue.

If the queue is not e mpty, the eleme nt is re moved through ITEM and s ubsequently F RONT is

inc re mented by 1.

/*C impleme ntation of Queue using

Arrays*/

#inc lude <stdio. h>

#inc lude <c onio.h>

#def ine MAX 5

int inse rt(); /* function prototypes */

int delete();

void display();

int queue[MAX], rea r = -1, front = - 1;

ma in()

");

printf("Queue Ove rflow \n");

else

{

if (front == - 1)

/*If queue is initia lly e mpty */

front = 0;

printf("Inset the ele ment in queue :

sc anf("%d", &a dd_it e m);

rear = rea r + 1;

queue[rear] = add_ite m;

}

return;

{

int c hoic e;

c lrsc r();

printf("Implme ntation of Queue\n");

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

while (1)

{

printf("1.Insert\n2. Delete\n3. Displa

} /*End of inse rt()*/

int delete()

{

if (front == - 1 || front > rea r)

{

printf("Que ue Underf low \n");

return ;

y\n4.Quit\n");

printf("Enter your c hoic e : ");

sc anf("%d", &c hoic e);

switc h (c hoic e)

}

else

{

printf("Ele me nt deleted from queue

{

c ase 1:

insert();

break;

c ase 2:

delete();

break;

c ase 3:

display();

break;

c ase 4:

exit(1);

} /*End of switc h*/

} /*End of while*/

} /*End of ma in()*/

int inse rt()

{

int add_ite m;

if (rear == MAX - 1)

is : %d\n", queue[front]);

front = front + 1;

}

return;

} /*End of delete() */

void display()

{

int i;

if (front == - 1)

printf("Que ue is e mpty \n");

else

{

printf("Que ue is : \n");

for (i = f ront; i <= rear; i++)

printf("%d ", queue[i]);

printf("\ n");

}

} /*End of display() */

2.6.1.2 Linke d Represe ntation

A linked queue is a que ue imple me nted as a linked list with two pointer variables F RONT and

REAR pointing to the nodes whic h is in the FRONT and REAR of the queue.

Page 11: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

Algo rithm : LINKQ_INSE RT(INFO, LINK, F RONT, REAR, ITE M, AVAIL).

This algorithm inserts an ele ment ITEM into a linked queue.

Step 1: [OVERF LOW ?]

If AVAIL := NULL, then:

Write: OVERFLOW and Exit.

Step 2: [Re move first node from AVAIL list.]

Set NEW := AVAIL, and

AVAIL := LINK[AVAIL].

Step 3: Set INFO[NEW] := ITEM, and

LINK[NEW] := NULL. [Copies ITEM into new node.]

Step 4: If FRONT = NULL, then:

Set FRONT := NEW and REAR := NEW.

[If Q is e mpty then ITEM is the first ele ment in the queue Q.]

Else:

Step 5: Exit.

Set LINK[REAR] := NEW, and

REAR := NEW.

[REAR points to the new node appended to the end of the list.]

Algorithm : LINKQ_DELE TE (INFO, LINK, F RONT, REAR, ITEM, AVAIL).

This algorithm de letes the front ele me nt of the linked queue and stores it in ITEM.

Step 1: [UNDERF LOW?]

If FRONT = NULL, then:

Write: UNDERFLOW and Exit.

Step 2:

Step 3: Set ITEM := INF O[F RONT].

Set NEW := F RONT, and [Save the data value of FRONT.]

[Reset FRONT to the next position.]

Step 4:

Step 5:

Set FRONT := LINK[F RONT].

Set LINK[NEW] := AVAIL, and

AVAIL := NEW

Exit.

[Add node to the AVAIL list.]

2.7 C IRC ULAR QUE UE

One of the ma jor proble ms w ith the linear que ue is the lac k of proper utilization of spac e.

Suppose that the queue c an store 10 ele me nts and the entire queue is full. So, it means that

the queue is holding 10 ele me nts. In c ase, some of the e le me nts at the front are deleted, the

ele me nt at the last position in the que ue c ontinues to be at the sa me pos ition a nd there is no

effic ient way to find out that the queue is not full.

Page 12: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

In this way, spac e utilization in the c ase of linear que ues is not effic ient. This proble m

is arising due to the representation of the queue.

The alternative represe ntation is to depic t the queue as c irc ular. In c ase, we are

representing the queue using a rrays, then, a queue w ith n ele me nts starts from index 0 and

ends at n- 1. So, c learly, the first ele ment in the que ue w ill be at index 0 a nd the last ele ment

will be at n-1 when all the pos itions between inde x 0 and n-1 (both inc lus ive) a re fille d. Unde r

suc h c irc umstanc es, front will point to 0 and rea r w ill point to n-1. Howeve r, whe n a new

ele me nt is to be added a nd if the rear is pointing to n-1, then, it needs to be c hec ked if the

position at inde x 0 is f ree. If yes, then the ele ment c an be added to that position a nd rear c an

be adjusted ac c ordingly. In this way, the utilization of s pac e is inc reased in the c ase of a

c irc ular queue.

In a c irc ula r que ue, front will point to one

position less to the first ele me nt. So, if the first

ele me nt is at position 4 in the array, then the front

will point to position 3. W hen the c irc ula r que ue is

c reated, then both front and rear point t o index 1.

Also, we c an c onc lude that the c irc ula r queue is

e mpty in c ase both front and rear point to the sa me

inde x. Figure depic ts a c irc ular que ue.

Enque ue(value) - Inse rting va lue into the

Circular Queue

Step 1: Chec k whether queue is FULL.

If ((REAR == SIZE-1 && F RONT == 0) || (FRONT == REAR+1))

Write “Queue is full ” and Exit

Step 2: If ( rear == SIZE - 1 && front != 0 ) then:

SET REAR := - 1.

Step 4: SET REAR = REAR +1

Step 5: SET QUEUE[REAR] = VALUE

Step 6: Exit and c hec k 'front == - 1' if it is TRUE, then set front = 0.

deQueue() - De leting a value from the Circula r Queue

Step 1: Chec k whether queue is EMPTY ?

If (FRONT == -1 && REAR == -1)

Write “Queue is e mpty” and Exit.

Step 2: DISPLAY QUEUE[F RONT]

Step 3: SET FRONT := F RONT +1 .

Step 4: If( FRONT = SIZE, then:

SET FRONT := 0.

Step 5: Exit

/* Program to implement Circula r

Queue us ing Array */

#inc lude <stdio.h>

#inc lude <c onio. h>

#def ine SIZE 5

int c insert(int);

int c delete();

void display();

int c q[SIZE], front = -1, rear = -1;

void main()

{

Page 13: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

int c hoic e, ele;

c lrsc r();

while(1){

printf("CIRCULAR QUEUE

IMPLEMENTATION\ n");

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

printf("****** MENU ****** \n");

printf("1. Inse rt\n2. De lete\n3.

Display\n4. Exit\n");

printf("Enter your c hoic e: ");

sc anf("%d", &c hoic e);

switc h(c hoic e){

c ase 1: printf("\nEnter the value to

be inse rt: ");

sc anf("%d",&e le);

c insert(ele);

brea k;

c ase 2: c delete();

brea k;

c ase 3: display();

brea k;

c ase 4: exit(1);

} /*End of switc h */

} /*End of while */

} /*End of main */

int c insert(int value)

{

if((front == 0 && rea r == SIZE - 1) ||

(front == rea r+1))

printf("\nCirc ular Queue is Full!

Inse rtion not possible!!!\n");

else{

if(rear == SIZE-1 && front != 0)

rear = -1;

c q[++rea r] = va lue;

printf("\nInse rtion Suc c ess!!!\n");

if(front == -1)

front = 0;

} /*End of c insert() */

int c delete()

{

if(front == - 1 && rea r == -1)

printf("\nCirc ular Queue is Empty!

De letion is not possible!!!\ n");

else{

printf("\nDe leted ele me nt :

%d\n",c q[front ++]);

if(front == SIZE)

front = 0;

if(front-1 == rea r)

front = rea r = -1;

}

return;

} /*End of c delete() */

void display()

{

if(front == - 1)

printf("\nCirc ular Queue is

Empty!!!\n");

else{

int i = f ront;

printf("\nCirc ular Queue Ele ments are :

\n");

if(front <= rear){

while(i <= rea r)

printf("%d\t",c q[i++]);

}

else{

while(i <= SIZE - 1)

printf("%d\t", c q[i++]);

i = 0;

while(i <= rea r)

printf("%d\t",c q[i++]);

}

}

return;

}

} /*End of display() */

Page 14: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

2.8 DOUBLE E NDE D QUE UE (DE QUEUE)

A Dequeue is a homogeneous list of ele ments in w hic h inse rtions a nd de letion ope rations a re

performe d on both the ends. Bec ause of this prope rty it is know n as double e nded queue i.e.

De queue or dec k. De que has two types:

1. Input restric ted queue: It allows insertion at only one end

2. Output restric ted queue: It allows de letion at only one end

In dequeue four pointers are used. They are left front(lf), left rear(lr), right front(rf) and right

rear(rr).

If (lf ==lr) and (rf ==rr) then deque is empty.

If lr >rr then deque ue is full

For inse rting we have to modify rear poi nter. For deleting we have to modify front

pointer.

Always rea r pointer is 1 pos ition ahea d of last ele ment.

After insertion on left side, left rear should be inc re mented.

After insertion on right side, right rear should be dec re me nted.

Input Restricted Double Ende d Queue

In input restric ted double ended queue, the inse rtion ope ration is performed at only

one end and de letion ope ration is performed at both the ends.

Output Restricted Double Ended Queue

In output restric ted double ended que ue, the deletion ope ration is performed at only

one end and inse rtion ope ration is performed at both the ends.

2.9 PRIORITY QUEUE

Def: Pr iority queue is a variant of queue data struc ture in whic h insertion is performed in the

order of arrival and de letion is performed based on the priority.

In priority queue every ele ment is assoc iated with some priority. Normally the priorities are

spec ified using numeric al values. In some c ases lower values indic ate high priority and in

some c ases highe r values indic ate high priority

In priority queues ele ments are proc essed acc ording to their priority but not acc ording to the

orde r they are entered into the queue.

Page 15: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

For exa mple, let P be a priority queue w ith three e le me nts a, b, c whose priority factors are

2,1,1 respec tively. He re, larger the numbe r, higher is the priority ac c orded to that ele me nt.

When a new e le ment d with highe r priority 4 is inse rted, d joins at the head of the queue

superse ding the re ma ining ele me nts. When e le ments in the queue have the sa me priority,

then the prio rity queue behaves as an ordina ry queue following the princ iple of FIFO a mongst

suc h ele ments.

The working of a priority que ue may be like ned to a s ituation when a f ile of patients wa its for

their turn in a que ue to have a n appoint ment w ith a doc tor. All patients are ac c orded equa l

priority and follow an FCFS sc he me by appoint me nts. However, whe n a patient with bleeding

injuries is brought in, he/s he is ac c orded highe r priority and is imme diately moved to the head

of the queue for imme diate attention by the doctor. This is priority queue at work.

There are two types of priority queues they are as follows...

1. Max P riority Queue

2. Min P riority Queue

Max Priority Queue

In ma x priority queue, ele ments are inse rted in the order in whic h they arrive the

queue a nd always ma ximum value is re moved f irst from the queue. For e xa mple assume that

we insert in orde r 8, 3, 2, 5 and they are re move d in the orde r 8, 5, 3, 2.

There are two representations of ma x priority queue.

1. Using One- Way List Representation

2. Using an Array

One-Way List Re presentation

One way to ma intain a priority queue in me mory is by means of a one -way list, as follows:

1. Eac h node in the list will c ontain three ite ms of information:

1. an information Feld INFO

2. a priority number P RN, and

3. a link numbe r LINK

2. A node X prec edes a node Y in the list

a. when X has highe r priority than Y or

b. when both have sa me priority but X was added to the list before Y

Fig.: Representation of Linke d list

Algorithms for insertion and deletion

Insertion: F ind the loc ation of Inse rtion

Step 1: Add an ITEM with priority numbe r N

Step 2: Traverse the list until finding a node X whose priority exc eeds N. Insert ITEM in front

of node X.

Step 3: If no suc h node is found, insert ITEM as the last eleme nt of the list.

Deletio n: Delete the first node in the list.

Page 16: Data Structures(R16) UNIT- II 2.1 STAC Kstmarysguntur.com/cse materials/ds/UNIT_II.pdfLike a rray a nd linke d list, stac k is also a linear data structure, but the only differenc

Data Structures(R16) UNIT- II

Array re presentation

Separate queue for eac h level of priority.

Eac h queue will appear in its own c irc ular a rray and must have its own pair of pointers,

FRONT and REAR.

If eac h queue is given the sa me a mount spac e then a 2D que ue c an be used

Deletion Algorithm

Fig. Array Representation with multiple queues

Step 1: Find the s mallest K suc h that FRONT[K] ≠ NULL

Step 2: Delete and proc ess the front ele ment in row K of QUEUE

Step 3: Exit

Insertion Algorithm

Step 1: Insert ITEM as the rear ele ment in row M of QUEUE

Step 2: Exit

Min Priority Queue

In min priority queue, ele ments are inserted in the order in whic h they arrive the queue

and a lways minimu m va lue is re moved f irst from the queue. For e xa mple assume that we

inse rt in order 8, 3, 2, 5 a nd they are re moved in the orde r 2, 3, 5, 8.