Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked...

23
Darshan Institute of Engineering & Technology for Diploma Studies Unit 3 1 Dept: CE DS (3330704) Vishal K. Makwana Linear and Non-Linear Data Structures Linear data structure: Linear data structures are those data structure in which data items are arranged in a linear sequence by physically or logically or both the ways. E.g. – array, linked list. Non-Linear data structure: Non linear data structures are those data structure in which data items are not arranged in a sequence. E.g. – graph, tree. Stack A stack is a data structure in which elements are added and removed from one end, Last in first out structures (LIFO). In this list insertion and deletions are made at one end called top of stack. For example, consider is a stack of plates on the counter in cafeteria, during the time of dinner, customers take plates from the top of the stack and waiter puts the washed plates on the top of the stack. So a new plate is put on top and old one is yet bottom. Most micro-processor use a stack based architecture. When member function is called it return address and arguments pushed into a stack and when function returns they are popped off. The stack operations are built into the micro-processor. 1) Array- Representation of a stack: Top of Stack Top Top Bottom of Stack Bottom X X X X X X Bottom of Stack Top of Stack X Unused Elements ( Vertical representation of stack )

Transcript of Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked...

Page 1: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

1 Dept: CE DS (3330704) Vishal K. Makwana

Linear and Non-Linear Data Structures

Linear data structure: Linear data structures are those data structure in which data items are arranged in a linear

sequence by physically or logically or both the ways.

E.g. – array, linked list.

Non-Linear data structure: Non linear data structures are those data structure in which data items are not arranged in a

sequence.

E.g. – graph, tree.

Stack A stack is a data structure in which elements are added and removed from one end, Last in first

out structures (LIFO).

In this list insertion and deletions are made at one end called top of stack.

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

customers take plates from the top of the stack and waiter puts the washed plates on the top of

the stack.

So a new plate is put on top and old one is yet bottom.

Most micro-processor use a stack based architecture. When member function is called it return

address and arguments pushed into a stack and when function returns they are popped off. The

stack operations are built into the micro-processor.

1) Array- Representation of a stack:

Top of Stack Top

Top

Bottom of Stack

Bottom

X

X

X

X

X

X

Bottom of Stack

Top of Stack

X

Unused Elements

( Vertical representation of stack )

Page 2: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

2 Dept: CE DS (3330704) Vishal K. Makwana

The operation in a stack is representation by using vector consisting of number of elements.

A pointer top keeps of the top elements, when stack is empty top has a value 0.

Every time a new element is added at top, top is incremented by one.

When an element is deleted from a top, top is decremented by one.

2) PUSH and POP Operation on Stack: The stack as an abstract data type (ADT), the operation that add an element to the top of stack is

usually called PUSH operation.

The operation that takes the top element from the top of stack is called POP operation.

When we begin using stack, it should be empty so another necessary operation is one that creates

an empty stack. This operation is known as create stack.

We must also check that whether a stack contains any elements before we pop it from the stack.

We also perform a operation that destroy a stack for leaving the stack empty , this is known as a

destroy stack operation.

Example: The effect of PUSH and POP operation are easilyunderstand by below:

1. Create stack(empty) or clear stack Empty Stack

2. Push stack (Block 1) push

3. Push (stack, Block 2)

4. Push (stack, Bock 3)

5. Pop (stack X) pop the top block

& put it into X

6. Pop (stack X)

1

2

1

3

2

1

2

1 3 X

1

Top

Top

X X X --- X X

Bottom of Stack Free Space Top of Stack

( Horizontal representation of stack )

Page 3: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

3 Dept: CE DS (3330704) Vishal K. Makwana

1) PUSH Operation:

o In push operation, we can add element to the top of the stack.

o So before push operation we must check the stack, it should not be a full.

o If stack is already full and when we try to add an element then stack overflow error occurs.

o It is called ‘Stack Overflow’ condition.

PUSH (S, Top, X)

o This function insert an element X to the top of stack which is represented by a vector S containing

N elements with Top pointer at top element in the stack.

o The first step of algorithm checks for overflow condition.

o If stack is full means Top pointer value reach at size of stack then insertion can’t be performed.

o In second and third step, if stack is not full a Top pointer value increment by one and insert a value at the Top pointer element.

2) POP operation:

o In pop operation, we can remove a element from top of the stack.

o So before pop operation, user must check the stack should not be a empty.

o If stack is empty and we try to pop an element then a stack underflow error occurs.

o It is called ‘Stack Underflow’ condition.

Algorithm : POP (S,Top) Step 1 : [check for under flow or check whether the stack is empty] If (Top=0) OR (Top=-1) then write(“Stack under flow”) Exit Step 2 : [Decrement pointer/remove the top information] Value S [Top]

Top Top – 1 Step 3 : [Return former top element of the stack] write(value) Step 4 : [Finished] Exit

Algorithm : PUSH(S,Top,X) Step 1 : [ Check for stack over flow] If Top >= N then write(“stack over flow”) Exit Step 2 : [increment Top pointer by value one] Top Top+1 Step 3 : [perform Insertion] S [Top] X Step 4 : [Finished] Exit

7. Push (stack X)

2 1

2

X

Page 4: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

4 Dept: CE DS (3330704) Vishal K. Makwana

POP (S, Top)

o This function removes an element from the top of the stack which is represented by a vector S

containing N element with a Top pointer at top element in the stack.

o The first step of algorithm checks for an underflow condition.

o If stack is empty means top pointer value is Zero, so we can’t pop the element.

o In second and third step, if stack is not empty then a top element value stored in a variable value

and then decremented top pointer by one and then returns at former top element of the stack.

3) Implementation of Stack: o A stack is a list and list can be implemented by two ways:

Array (Static Implementation)

Pointer (linked List / Dynamic Implementation)

Program of Static Implementation of stack: #include<stdio.h> #include<conio.h> #include<process.h> #define MAX 10 int push(int [],int,int); int pop(int [],int,int); void display(int [],int,int); int main() { int s[MAX],TOP=-1,choice,x,i; printf("\n Enter the choice for stack operation\n"); printf("1.PUSH\n"); printf("2.POP\n"); printf("3.DISPLAY\n"); printf("4.EXIT\n"); printf("Enter your choice\n"); scanf("%d",&choice);

do { switch(choice) { case 1 : TOP=push(s,TOP,x); break; case 2 : TOP=pop(s,TOP,x);

break; case 3 : display(s,TOP,x); break; default : exit(0);

} printf("\n Enter the choice for stack operation\n"); printf("1.PUSH\n"); printf("2.POP\n");

printf("3.DISPLAY\n"); printf("4.EXIT\n");

printf("Enter your choice\n");

Page 5: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

5 Dept: CE DS (3330704) Vishal K. Makwana

scanf("%d",&choice); } while((choice>0) || (choice<=4)); return 0; } int push(int s[],int TOP,int x) { printf("Top is:: %d",TOP); if(TOP == MAX) { printf("STACK IS OVER FLOW"); } else { printf("\nenter the item to be insert in stack"); scanf("%d",&x); TOP=TOP+1; s[TOP]=x; } return TOP; } int pop(int s[],int TOP,int x) { if(TOP<0) { printf(" STACK IS UNDER FLOW"); } else { x=s[TOP]; TOP=TOP-1; printf("\n Item to be deleted from stack are:"); printf("%d",x); } return TOP; } void display(int s[],int TOP,int x) { int i; if(TOP==-1) { printf("\n STACK IS EMPTY"); } else { printf("\n stack data are:"); for(i=TOP;i>=0;i--) { printf("%d\n",s[i]); } } }

Page 6: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

6 Dept: CE DS (3330704) Vishal K. Makwana

4) Application of Stack: Recursion is an important functionality in many progrmming language such as PASCAL, C etc.

Stack machine, certain computers performs stack operation at the hardware or machine level.

Compailation of infix expression into object code.

Representation of Polish Notation.

5) Infix, Prefix and Postfix Forms of Expressions:

Polish Notation:

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

The process of writing the operations of an expression either before their operands or after

operands are called the Polish Notation.

The polish notation are classified into three categories:

a) Infix

b) Prefix

c) Postfix

a) Infix:

o When the operators exist between two operands then the expression is called Infix

Expression.

o Consider the sum of A and B, we apply operator “+” between two operands and write the

expression sum as A+B.

o This expression is called Infix Expression.

b) Prefix:

o When the operator is written before their operand then the resulting expression is called

Prefix Expression.

o The operator precedes the two operands, +AB are prefix polish notation of sum.

c) Postfix:

o When an operator comes after their operands the resulting expression is called postfix

expression.

o It is also called reverse Polish Notation.

o The operator follows the two operands, AB+ is called postfix or reverse polish notation.

Rules for converting Infix Notation to the postfix / prefix notation:

1) The operation with highest precedence is converted first and then after a portion of the

expression has been converted to postfix.

2) It is to be treated as single operand.

3) We consider five binary operation, such are (+) addition, subtraction (-), multiplication (*),

division(/) and exponentiation.

The first four are available in C/C++, the fifth exponentiation will be represented by

the operator $ or .

The value of expression A$B or A B is A raise to B power, for example 3 2 = 9.

4) Take only two operands at a time to convert in a postfix from like A + B AB+

5) Always convert the parenthesis first.

6) Convert postfix exponentiation second if there are more than one exponentiation in sequence

then take order from right to left.

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

Page 7: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

7 Dept: CE DS (3330704) Vishal K. Makwana

8) Convert in postfix as addition and subtraction left to right. For Example: 1) Convert in to postfix (A + B) * C infix form

= (AB+) * C Convert addition first because it has parenthesis and it convert first

= (AB+)C* Convert the multiplication = Postfix form

2) A + (B * C) Infix form / take first parenthesis = A+ (BC*) Convert multiplication = A(BC*)+ Convert addition = Postfix form

Thumb rules for the conversion process are that operator with highest precedence are converted first.

Convert following Infix expression in to prefix & postfix form:

Solution: Postfix form conversion

1) A + B - C

= A B + - C

= A B + C –

2) ( A + B ) * ( C – D)

= ( AB+)* (C D-)

= (AB+) (CD-)*

= A B + C D - *

Example: Convert following expression in to postfix / reverse polish notation a + (b * c - (m / n p) * t) * s Step 1: a + (b * c - (m / n p ) * t) * s

Step 2: a + (b * c - (m n p / ) * t) * s

Step 3: a + (b c* – (m n p / ) *t) * s

Step 4: a + (b c* m n p / t * - ) *s

Step 5: a + b c * m n p / t * - s *

Step 6: a b c * m n p / t * - s * + Postfix expression

AB+C*

ABC*+

Infix Prefix Postfix

1) A + B – C - + A B C A B + C –

2) ( A + B ) * ( C – D ) * + A B - C D A B + C D - *

3) A $ B * C - D + E / F / ( G + H ) + - * $ A B C D // E F + G H A B $ C * D – E F / G H + / +

4) ( ( A + B ) * C – (D - E )) $ - * + A B C – D E + F G A B + C * D E - - F G + $

$ (F + G)

5) A – B / (C * D $ E ) - A / B * C $ D E A B C D E $ * /

Page 8: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

8 Dept: CE DS (3330704) Vishal K. Makwana

Each operation in a postfix string refers to the previous two operands in a string.

Each time we read an operand and we push it into stack.

When we reach on operator, its operand will be the top two element on the stack.

We can then pop these two element, perform the indicated operation on them and push the

result on the stack.

So that it will be available for use as an operand of the next operator.

Algorithm to convert infix expression into postfix polish notation : Algorithm : INFIX TO POSTFIX CONVERSION Step 1: define the opndstk as an empty stack Step 2: Scan the infix string as an input string with one by One character reading method . Step 3: While (not end of input string)

Fetch one character form input (repeat) string and Store it in to symb variable check whether this symb is an operator or an operand.

If (symb is an operand) Then

Evaluating a postfix operation : Algorithm: Postfix expression Step 1: opndstk empty stack Step 2: [Scan the input string for reading one] While (not end of input) repeat step 3 Symb next to input character Step 3: [check for operand] If (symb is an operand) Then PUSH (opndstk,symb)

Else Opnd2 POP (opndstk) [opnd1 and opnd2 are Variables] Opnd1 POP (opndstk) Value result of applying symb to opnd 1 & Opnd 2 push (opndstk, value) Step 4: POP (opndstk) Step 5: [Finished] Exit

3) A $ B * C - D + E / F / ( G + H)

= A $ B * C - D + E / F / (G H+)

= (A B $) * C - D + E / F / (G H+)

= (A B $ C * - D ) + (E F / G H + /)

= A B $ C * D - E F / G H + / +

4) (( A + B ) * C - (D - E)) $ (F + G)

= (( A B +) * C - ( D E -)) $ ( F G +)

= ( A B + C * D E - - ) $ (F G +)

= A B + C * D E - - F G + $

5) A - B / (C * D $ E)

= A - B / (C * D E $)

= A - B / (C D E $ *)

= A - B C D E $ * /

= A B C D E $ */ -

Page 9: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

9 Dept: CE DS (3330704) Vishal K. Makwana

6) Recursion Functions: Recursion means a function call itself.

Example: The factorial function can be recursively defined as,

Here, FACTORIAL(N) is defined in terms of FACTORIAL(N-1) which is again defined interms of

FACTORIAL(N-2) and this process continue until FACTORIAL(0) is reached.

The value of FACTORIAL(0) is defined as 1.

There are two important condition that must be satisfied by any recursive function :

1) Each time a function calls itself, it must be “nearer ” in some sense of solution.

2) Terminating condition must be there which can terminates the chain of process.

To find factorial value using Recursion. #include <stdio.h> #include <conio.h> main() { int I,n,a; int fact(int); printf(“\n enter the value of n:”); scanf(“%d”,&n); a=fact(n); printf(“\n the factorial value of n: %d”,a); } int fact(int x) { int f=1;

if (x==1) return (f);

else f=n * fact ( n-1 ); return (f); }

Factorial (N) =

1

N * FACTORIAL (N - 1) If N > 0

If N = 0

PUSH that symb to postfix string post. Else If it is not operand Then check precedence of that fetch symb If precedence is true Then PUSH that symb to a postfix string Do this step until the while condition cannot failed Step 4: now push the symb to opndstk Step 5: [Finished]

Exit

Page 10: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

10 Dept: CE DS (3330704) Vishal K. Makwana

7) To Generate the Fibonacci number using recursion: A fibonacci series is,

0 1 1 2 3 5 8 ………………….. N

If we consider F0 = 0 and F1 = 1 then F2 = F0 + F1 = 0 + 1 = 1, similar F3 = F2 + F1 = 1 + 1 = 2, and

F4 = F3 + F2 = 2 + 1 = 3 and so on.

It is clear that each succeeding(next) term is the sum of two preceeding(previous) terms, doing

this procedure until i becomes less then the value of n.

8) Greatest Common Divisor (GCD): To implement Greatest Common Divisor(GCD) function in a recursive form using following steps:

a) If m <= n and n % m = 0 then gcd(n, m) = m(Termination step).

b) If n < m then gcd(n, m) = gcd(m, n) ( Recursive definition of gcd)

c) If n >= m then gcd(n, m) = gcd(m, n % m) (Recursive definition of gcd)

Using these 3 rules, the recursive program of greatest common divisor can be written as below:

To Generate the Fibonacci number using recursion. #include <stdio.h> void main() { int fibo (int); /* function prototype */ int no, i=0; print (“enter the number of steps to generate fibonacci series :”); scanf(“%d”, &no); while(i<no) { printf(“%d\t”,fib(i)); i++; } } int fib(int n) {

if(n==1) ¦¦ (n==0) return (0);

else if (n==2) return (1);

else return (fib (n-1) + fib (n-2));

}

0

1

If n =0 or n = 1

If n = 2 Fibo_no (n) =

Fibo_no (n-1) + Fibo_no (n-2) if n > 2

Page 11: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

11 Dept: CE DS (3330704) Vishal K. Makwana

Queue

A data structure in which elements are added to one end (rear) and removed from the other end

(front) in FIFO (First In First Out) structure.

Queue is a data structure that is similar to a stack.

But difference is , in a queue to first item inserted is the first to be removed (FIFO).

In stack the last item is the first to be removed (LIFO).

In queue always addition occurs at rear end and deletion at front end.

1) Array – Representation of Queue:

A queue has two pointer, from pointer and rear pointer which are pointing to front and rear

element of the queue.

Elements

#include <stdio.h> int gcd( int ,int); void main() {

int n,m,divisior; printf(“enter the two numbers”); scanf(“%d%d”,&n,&m); divisior=gcd(n,m); printf(“the greatest common factor of %d and %d is %d”,n,m,divisior); return 0; } int gcd(int n,int m) {

if(m<=n&&n%m==0) retuen m;

if(n<m) return gcd(m,n) else return gcd(m,n%m); }

Exit

Deletion

Entry

Insertion Rear end

Front end

(Queue)

Page 12: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

12 Dept: CE DS (3330704) Vishal K. Makwana

2) Operation on Queue: a) PUSH

b) POP

Consider a queue consist of N elements and an element value, which we can insert and delete

value from the queue.

The value NULL (= -1)of front pointer indicate that queue is empty, so we can not perform

delete operation.

If rear pointer value is increase and it becomes grater than N (no of element) rear >= N

indicates queue is full. So we can not perform insertion operation.

How to insert and delete value from the queue and see the position of front and rear pointer

in below figure:

i) Delete first element from queue:

When we remove the element value from a queue, a pointer value is increment by one.

Front = Front + 1

ii) Insert one element in a queue:

(Rear=Rear + 1 )

4

Front

Point

er

Rear

Point

Front

Point

er

Rear

Point

(Front=Front + 1 )

3 2 1

Rear

22

Front

0

11 33 44 - - -

(Queue in memory)

Insertion Deletion

Front Pointer

Rear

Pointer

X X X - - -

(Vector representation of Queue)

2 3 1 0

22 33 44 - - -

2 3 1 0

22 33 44 - - - 55

Page 13: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

13 Dept: CE DS (3330704) Vishal K. Makwana

When we insert an element at rear end in a queue, a rear pointer value is increment by

one.

Rear = Rear + 1

3) Static Implementation of Queues: For writing an algorithm we can define following variables:

S -> It is an array having N elements.

Rear -> It is pointer which will point to last (Rear) end of queue.

Front -> It is pointer which will point to first (front) end of queue.

X -> It is variable which will store the value that we want to push or pop from the

queue.

1) PUSH (Insertion):

If we push or insert an element in a queue at rear end and rear pointer vlaue increment by

one(1).

The first step of algorithm is to check the overflow condition.

If queue is already full means rear >= N (Size) and if we try to insert an element in queue then

it will indicate an ‘Overflow’ error.

In second step, if queue is not full then we can insert an element in queue. So rear pointer

value is increment by one.

In third step, perform value of variable X put on to the rear(last) element of queue.

Algorithm: PUSH(S, front, rear, x) Step 1: [Check for Queue ‘Over flow’] if rear >=size then write (“Queue is over flow”) Exit Step 2: [Increment Rear Pointer] Rear <- rear + 1 Step 3: [Insert an element at rear of Queue] S [rear] <- x Step 4: [Set the front pointer] if front = -1 then front <- 0 step 5 : [Finished] Exit

Page 14: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

14 Dept: CE DS (3330704) Vishal K. Makwana

2) POP (Deletion):

If we delete or pop an element from queue at front end and front pointer value increment by

one.

The first step in an algorithm is to check the underflow condition.

If queue is empty (front = -1) and if we try to delete an element from queue then it will

indicate an ‘underflow’ error.

In forth step, If queue is not empty and we want to delete an element from queue. So front pointer value will increment by one.

Program of static Implementation of a queue for Insert & Delete Operation.

#include<stdio.h> #include<process.h> void Qpush(); void Qpop(); void Qdisplay(); int q[50],front = -1,rear = -1,N,choice; int main() { printf("Enter size of queue:: "); scanf("%d",&N); printf("Enter ur choice:: \n"); printf("1. Push\n"); printf("2. Pop\n"); printf("3. Display\n"); printf("4. Exit\n"); scanf("%d",&choice);

do {

Algorithm : POP (S, front, rear, x) Step 1: [Check for Queue ‘Under flow’] if (front =-1 OR front = 0) Then Write(“Queue is under flow”) Exit Step 2: [Remove an element from queue] x <- S [front] Step 3: [Print the popped element] Write (“x”) Step 4: [Check for empty queue] if front = rear then front <- 0 rear <- 0 else front <- front + 1 Step 5: [Finished] Exit

Page 15: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

15 Dept: CE DS (3330704) Vishal K. Makwana

switch(choice) { case 1: Qpush(); break; case 2: Qpop(); break; case 3: Qdisplay(); break; default: exit(0); } printf("Enter ur choice:: \n"); printf("1. Push\n"); printf("2. Pop\n"); printf("3. Display\n"); printf("4. Exit\n"); scanf("%d",&choice); }while(choice>0 || choice<=4); return 0; } void Qpush() { int x; if(rear == N-1) { printf("Queue is overflow\n"); } else { printf("Enter ur item to be insert in queue:: "); scanf("%d",&x); if(front == -1) { front = 0,rear = 0; } else { rear = rear + 1; } printf("Rear is:%d \n",rear); q[rear] = x; } } void Qpop() { int x; if(front == -1 || front > rear) { printf("Queue is underflow\n"); }

Page 16: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

16 Dept: CE DS (3330704) Vishal K. Makwana

4) Trace of Simple Queue: The following figures clearly indicate the PUSH and POP operation performed on a queue

which will display the front and rear pointer position.

Insert 41

Front Rear

Front Rear

Front Rear

41

41 51

Insert 51

Empty Queue

else { printf("Ur poped element is:: %d",q[front]); front = front + 1; printf("Front is:%d \n",front); } } void Qdisplay() { int i; if(front == -1) { printf("Queue is underflow"); } else { printf("Ur elements of queue are::\n"); for(i=front;i<=rear; i++) { printf("%d\n",q[i]); } } }

Page 17: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

17 Dept: CE DS (3330704) Vishal K. Makwana

In a last stage, if rear pointer value is same as size of queue (Rear = Size) means rear pointer

points to end of array.

Now, suppose we try to insert an element (Value <- 101) into queue then this can be done by

moving entire queue to beginning of array.

By changing front and rear pointer value accordingly and then insert an element into queue.

But for array, such operation is time consuming and expensive.

So this type of problem can be solved by using new concept which is called Circular Queue.

Front Rear

Front Rear

Front Rear

Front Rear

Front Rear

41 51 61

41 51 61 71

51 61 71

61 71

61 71 81

Insert 61

Insert 71

Remove 41

Insert 81

Remove 51

Front Rear

Front Rear

61

71 81 91

61 71 81 91 101

Insert 101

Insert 91

Page 18: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

18 Dept: CE DS (3330704) Vishal K. Makwana

5) Limitation of Single Queue: In a linear queue, frequently we face the problem of overflow of a queue.

If queue contain maximum element and we want to insert a new element then this type of

problem can be solved by using Circular Queue instead of Linear Queue.

Concepts of Circular Queue:

Let we have an array Q, that contain N elements in which Q[1] comes after Q[n] in the array.

This type of technique is used to construct a queue then queue is called Circular Queue.

A queue is called Circular Queue when last element comes just before the first element.

In circular queue, when rear pointer is rear = n (Maximum size) and if we try to insert an element

then this element assigned to Q[1] instead of increasing rear pointer to n + 1.

We reset the rear pointer to 1.

Similarly, if front pointer value reach its maximum value (n), front = n and if we remove element

from queue then we reset a front pointer to 1 instead of n + 1.

Suppose a queue contains only one element that is front = rear <> Null and then we remove an

element then front and rear pointer are now assign to Null to indicate that queue is empty.

Trace of Circular Queue:

To indicate the position of front and rear pointer from below figures,

Insert 99

Front Rear

Front Rear

99

99 109

Insert 109

Q[n]

Q[n-1]

Q[1]

Q[2]

- - - - - - -

[Circular Queue]

Page 19: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

19 Dept: CE DS (3330704) Vishal K. Makwana

Remove 119

Insert 119

Front Rear

Front Rear

Front Rear

Front Rear

Front Rear

99 109 119

109 119

109 119 129

119 129

139 119 129

Remove 99

Insert 129

Insert 139

Remove 109

Reset rear Pointer to 1, rear=1

Front Rear

Front Rear

139 149 119 129

139 129

Insert 149

149

Front Rear

139 149

Remove 129

Reset front Pointer to 1, front=1

Page 20: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

20 Dept: CE DS (3330704) Vishal K. Makwana

Static Implementation of circular Queues:

(B) POP(Deletion): Algorithm: POP(s, front, rear, X) Step 1: [Check for “under flow”] If front= -1 Then write(“circular queue is under flow”) Exit Step 2: Remove an element from circular queue X <- s[front] Step 3: [Print the popped Element] Write(“x”) Step 4: [check whether circular queue is empty or not] If(front = rear) Then front <- -1 rear <- -1 Step 5: [Check front pointer position] Else if front = size Front <- 0 (Reset front pointer) Else Front <- front + 1 Step6: [Finished] Exit

(A) PUSH(Insertion): Algorithm: PUSH(s, front, rear, x) Step 1: [Check for circular Queue ‘Over flow’]

If front = 0 and rear = n-1 Then

Write (“circular queue is over flow”) Exit

Step 2: [Insert Elements in the circular Queue] Else if front = -1 and rear = -1 Front <- 0 Rear <- 0 S[rear] <- x

Step 3: [Check if the rear at the end of circular queue] Else if front <> 0 and rear = n-1

Rear <- 1[Reset rear pointer] S[rear] <- x

Step 4: [Insert the element in circular Queue] Else rear <- rear+1 S[rear] <- x

Step 5: [Finished] Exit

Page 21: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

21 Dept: CE DS (3330704) Vishal K. Makwana

Program of Static Implementation of Circular Queue for Insertion and Deletion operation.

#include<stdio.h> #include<process.h> void CQpush(); void CQpop(); void CQdisplay(); int s[10],N,choice,front = -1,rear = -1; int main() { printf("Enter size of circular queue\n"); scanf("%d",&N); printf("Enter one of following choice:: \n"); printf("1. Push\n"); printf("2. Pop\n"); printf("3. Display\n"); printf("4. Exit\n"); scanf("%d",&choice); do { switch(choice) { case 1: CQpush(); break; case 2: CQpop(); break; case 3: CQdisplay(); break; default: exit(0); } printf("1. Push\n"); printf("2. Pop\n"); printf("3. Display\n"); printf("4. Exit\n"); scanf("%d",&choice); }while(choice>0 || choice<=4); return 0; } void CQpush() { int x; printf("Enter ur element to inser in the circular queue::"); scanf("%d",&x); if((front == 0 && rear == N-1) || rear == front-1 ) { printf("Queue is overflow\n"); } else if(rear == N-1 && front !=0) { rear=0;

Page 22: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

22 Dept: CE DS (3330704) Vishal K. Makwana

s[rear]=x; } else if(front == -1 && rear == -1 ) { rear = 0; front = 0; s[rear]=x;

} else { rear = rear +1; s[rear] = x; } printf("Rear value is:: %d\t & front value is:: %d\n",rear,front); } void CQpop() { int x; if(front == -1 ) { printf("Queue is underflow\n"); } x = s[front]; printf("Element to be poped is :: %d\n",x); if(front == rear ) { front = -1;rear = -1; } else { if(front == N-1) { front = 0; } else { front = front + 1; } } printf("Rear value is:: %d\t & front value is:: %d\n",rear,front); } void CQdisplay() { if(front != -1 && rear != -1) { if(front<=rear) { printf("Elements of queue are::\n"); for (int i=front; i<=rear;i++)

Page 23: Linear and Non-Linear Data Structures and Non-Linear Data Structures ... E.g. – array, linked list. Non-Linear data structure: ... Array- Representation of a stack:

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

23 Dept: CE DS (3330704) Vishal K. Makwana

Application of Queue

Queue is widely used in simulation work.

In mailbox application when we save the message to communicate between two user or processes in

a system is work according to queue.

A computer processor also maintain buffers in the form of queue for incoming resources requests.

In operating system, process scheduling or disk scheduling algorithms uses queue concept.

{ printf("%d\n",s[i]); } } else { printf("Elements of queue are::\n"); for(int i=front; i<N; i++) { printf("%d\n",s[i]); } for(int i=0;i<=rear;i++) { printf("%d\n",s[i]); } } } }