0% found this document useful (0 votes)
14 views56 pages

RAA DS Unit 2 Final Print

The document provides an overview of stacks and queues, focusing on the stack as a last-in-first-out (LIFO) data structure, its operations, and various implementations using arrays and linked lists. It details the algorithms for inserting and deleting elements, as well as the structure of stack data types. Additionally, it includes example programs in C for stack implementation using both arrays and linked lists.

Uploaded by

patilakshay4522
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views56 pages

RAA DS Unit 2 Final Print

The document provides an overview of stacks and queues, focusing on the stack as a last-in-first-out (LIFO) data structure, its operations, and various implementations using arrays and linked lists. It details the algorithms for inserting and deleting elements, as well as the structure of stack data types. Additionally, it includes example programs in C for stack implementation using both arrays and linked lists.

Uploaded by

patilakshay4522
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

UNIT – II

STACK & QUEUE


The Stack
Stack is a last-in-first-out (LIFO) data structure. It is a queue with only one end
(i.e. new items enter at the same point as old items leave). Items leave a stack in the
reverse order in which they arrive. A LIFO queue is the same as a ‘stack’ in conventional
English. If you pile books on top of each other and then remove them from the top, it
behaves exactly like a stack. In a computer a stack can be used in many ways. However,
we are interested in the following three applications of the stack:
1. Storing subroutine return addresses.
2. Passing parameters from a program to a subroutine.
3. Providing temporary storage (local workspace) in a subroutine.
A stack is a LIFO structure. The various operations on Stack are:
 PUSH : Enter item at top of stack.
 POP : Remove item from top of stack.
 To check which element is at the top of the stack.
Additional primitives can be defined as:
 IsEmpty : Reports whether the stack is empty.
 IsFull : Reports whether the stack is full.
 Initialize : Creates/initializes the stack.
 Destroy : Deletes the contents of the stack.
An abstract data type in the STACK family often includes the following five operations.
1. MAKENULL(S). Make stack S be an empty stack. This operation is exactly the
same as for general lists.
2. TOP(S). Return the element at the top of stack S. If, as is normal, we identify the
top of a stack with position 1, then TOP(S) can be written in terms of list
operations as RETRIEVE(FIRST(S), S).
3. POP(S). Delete the top element of the stack, that is, DELETE(FIRST(S), S).
Sometimes it is convenient to implement POP as a function that returns the
element it has just popped, although we shall not do so here.
4. PUSH(x, S). Insert the element x at the top of stack S. The old top element
becomes next-to-top, and so on. In terms of list primitives this operation is
INSERT(x, FIRST(S), S).

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 1
UNIT – II
5. EMPTY(S). Return true if S is an empty stack; return false otherwise.
The following diagram represents the working of the Stack:

Fig: Operations on Stack.


Example:

Where, TOS is the Top of Stack.


ALGORITHMS
A) INSERTING AN ELEMENT IN THE STACK
Procedure: PUSH(S, TOP, X).
This procedure inserts an element X to the top of the stack which is represented
by a vector S containing N elements with a pointer TOP denoting the top most element
in the stack.
Check for Stack Overflow.
if TOP >= N
then
WRITE (‘STACK OVERFLOW’)
Return
1. Increment TOP Pointer, TOP <- TOP + 1
2. Inset Element, S[TOP] <- X

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 2
UNIT – II
3. Finished.
Return
The first step of this algorithm checks for an overflow condition. If such a
condition exists, then the insertion cannot be performed on the stack and appropriate
error message occurs.

B) DELETING AN ELEMENT IN THE STACK


Procedure: POP(S, TOP).
This procedure removes the top element from the stack which is represented by
a vector S and returns this element. The TOP Pointer denotes the top most element in
the stack.

1. Check for Underflow on stack.


if TOP = 0
then
WRITE (‘STACK UNDERFLOW ON POP”)
Take action in response to underflow
Exit
2. Decrement TOP Pointer, TOP <- TOP - 1
3. Return former top element of the stack.
Return(S[TOP + 1])

The first step of this algorithm checks for an underflow condition. If such a
condition exists, then some appropriate action should take place

DATA STRUCTURES OF STACK


A stack is a special case of ordered list in which the insertion and deletion of the
elements are made at one end usually called as the stack top. The data structures used
are as:
 Arrays.
 Structure.
Declaration using Arrays:
The code to declare a stack using one-dimensional array is as follows:
#define size 100
int stack[size];
int top=-1;
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 3
UNIT – II
In the above code, stack is an array of integers and the most recent index of that
array will act as a top of the stack.
Initial top = -1. 0 1 2 3 4 --------------------- 98 99

Fig: Stack using one-dimensional array.


The size of the stack is 100. As we insert the elements in the stack, the top value
will be incremented. The first element will be placed from 0th position from the stack. At
the most we can store 100 elements in the stack, so the last element in the stack is at
{size of stack – 1}.

Declaration using Structures:


The code to declare a stack using structure is as follows:
#define size 10
struct stack
{
int s[size];
int top;
}st;

9 100

Top points here 2 30 Values in the


stack
1 20

0 10

Fig: Stack using Structure.


This method of declaration of stack is always preferred, because by this we are
binding the top variable with stack elements. Thus top and stack are associated with
each other by putting them together in a structure. The stack can be passed to the
function simply by passing the structure variable.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 4
UNIT – II
An Array Implementation of Stacks
Every implementation of lists we have described works for stacks, since a stack
with its operations is a special case of a list with its operations. The linked-list
representation of a stack is easy, as PUSH and POP operate only on the header cell and
the first cell on the list. In fact, headers can be pointers or cursors rather than complete
cells, since there is no notion of position" for stacks, and thus no need to represent
position 1 in a way analogous to other positions. However, the array-based
implementation of lists we gave in Section 2.2 is not a particularly good one for stacks,
as every PUSH or POP requires moving the entire list up or down, thus taking time
proportional to the number of elements on the stack. A better arrangement for using an
array takes account of the fact that insertions and deletions occur only at the top. We
can anchor the bottom of the stack at the bottom (high-indexed end) of the array, and
let the stack grow towards the top (low-indexed end) of the array. A cursor called top
indicates the current position of the first stack element. This idea is shown in Fig. 2.17.

Fig. 2.17. An array implementation of a stack.


For this array-based implementation of stacks we define the abstract data type
STACK by

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 5
UNIT – II

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 6
UNIT – II
EXAMPLE PROGRAM IN C TO IMPLEMENT STACK USING ARRAYS:
/*PROGRAM FOR IMPLEMENTATION OF STACK USING ARRAY*/
#include<stdio.h>
#include<conio.h>
#define maxsize 5
int stack[maxsize],top; //declaration of stack and top of the stack
int stack_full(); //function declaration of stack_full() function
int stack_empty(); //function declaration of stack_empty() function
void push(int);
int pop();
void stack_display(); //function declaration of stack_display() function

void main() //main function


{
int item1,choice;
char ans;
clrscr();
top=-1;
do
{
printf("\n\t************STACK OPERATIONS MAIN MENU************");
printf("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT");
printf("\n Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("\n\t Enter item to be pushed==>");
scanf("%d",&item1);
push(item1);
break;
}
case 2:
{
item1=pop();
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 7
UNIT – II
if(item1==-1)
printf("\n\t stack is empty..........");
else
printf("\n\t %d is poped from stack.",item1);
break;
}
case 3:
{
stack_display(); //function definition of stack_display() function
break;
}
case 4:
exit();
}
printf("\n \t CONTINYUE......(y/n):");
ans=getche();
}while(ans=='Y'|| ans=='y');
getch();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
int stack_full() //function definition of stack_full() function
{
if(top==maxsize-1)
return 1;
else
return 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
int stack_empty() //function definition of stack_empty() function
{
if(top==-1)
return 1;
else
return 0;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 8
UNIT – II
void push(int item2) //function definition of stack_push() function
{
if(stack_full()==1) //call of stack_full() function
printf("\n\t SORRY,item can not be pushed.stack is full...");
else
{
top++;
stack[top]=item2;
}
}
int pop()
{
int item3;
if(stack_empty()==1) //call of stack_empty() function
item3=-1;
else
{
item3=stack[top];
top--;
}
return item3;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
void stack_display() //function definition of stack_display() function
{
int i;
printf("\n\t display the stack.....");
for(i=top;i>=0;i--)
printf("\n\t%d",stack[i]);
}

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 9
UNIT – II
Linked list implementation of stack
Instead of using array, we can also use linked list to implement stack. Linked list
allocates the memory dynamically. However, time complexity in both the scenario is
same for all the operations i.e. push, pop and peek.
In linked list implementation of stack, the nodes are maintained non-contiguously in the
memory. Each node contains a pointer to its immediate successor node in the stack.
Stack is said to be overflown if the space left in the memory heap is not enough to create
a node.

The top most node in the stack always contains null in its address field. Lets discuss the
way in which, each operation is performed in linked list implementation of stack.
Adding a node to the stack (Push operation)
Adding a node to the stack is referred to as push operation. Pushing an element to a
stack in linked list implementation is different from that of an array implementation. In
order to push an element onto the stack, the following steps are involved.
1. Create a node first and allocate memory to it.
2. If the list is empty then the item is to be pushed as the start node of the list. This
includes assigning value to the data part of the node and assign null to the
address part of the node.
3. If there are some nodes in the list already, then we have to add the new element
in the beginning of the list (to not violate the property of the stack). For this

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 10
UNIT – II
purpose, assign the address of the starting element to the address field of the
new node and make the new node, the starting node of the list.

C implementation:
1. void push ()
2. {
3. int val;
4. struct node *ptr =(struct node*)malloc(sizeof(struct node));
5. if(ptr == NULL)
6. {
7. printf("not able to push the element");
8. }
9. else
10. {
11. printf("Enter the value");
12. scanf("%d",&val);
13. if(head==NULL)
14. {
15. ptr->val = val;
16. ptr -> next = NULL;
17. head=ptr;
18. }
19. else
20. {
21. ptr->val = val;
22. ptr->next = head;

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 11
UNIT – II
23. head=ptr;
24.
25. }
26. printf("Item pushed");
27.
28. }
29. }

Deleting a node from the stack (POP operation)


Deleting a node from the top of stack is referred to as pop operation. Deleting a
node from the linked list implementation of stack is different from that in the
array implementation. In order to pop an element from the stack, we need to
follow the following steps :
1. Check for the underflow condition: The underflow condition occurs
when we try to pop from an already empty stack. The stack will be empty
if the head pointer of the list points to null.
2. Adjust the head pointer accordingly: In stack, the elements are popped
only from one end, therefore, the value stored in the head pointer must be
deleted and the node must be freed. The next node of the head node now
becomes the head node.
Time Complexity : o(n)
C implementation
1. void pop()
2. {
3. int item;
4. struct node *ptr;
5. if (head == NULL)
6. {
7. printf("Underflow");
8. }
9. else
10. {
11. item = head->val;
12. ptr = head;
13. head = head->next;
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 12
UNIT – II
14. free(ptr);
15. printf("Item popped");
16.
17. }
18. }
Display the nodes (Traversing)
Displaying all the nodes of a stack needs traversing all the nodes of the linked list
organized in the form of stack. For this purpose, we need to follow the following
steps.
19. Copy the head pointer into a temporary pointer.
20. Move the temporary pointer through all the nodes of the list and print the
value field attached to every node.
Time Complexity : o(n)
C Implementation
1. void display()
2. {
3. int i;
4. struct node *ptr;
5. ptr=head;
6. if(ptr == NULL)
7. {
8. printf("Stack is empty\n");
9. }
10. else
11. {
12. printf("Printing Stack elements \n");
13. while(ptr!=NULL)
14. {
15. printf("%d\n",ptr->val);
16. ptr = ptr->next;
17. }
18. }
19. }
Menu Driven program in C implementing all the stack operations using linked list
:
1. #include <stdio.h>
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 13
UNIT – II
2. #include <stdlib.h>
3. void push();
4. void pop();
5. void display();
6. struct node
7. {
8. int val;
9. struct node *next;
10. };
11. struct node *head;
12.
13. void main ()
14. {
15. int choice=0;
16. printf("\n*********Stack operations using linked list*********\n");
17. printf("\n----------------------------------------------\n");
18. while(choice != 4)
19. {
20. printf("\n\nChose one from the below options...\n");
21. printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
22. printf("\n Enter your choice \n");
23. scanf("%d",&choice);
24. switch(choice)
25. {
26. case 1:
27. {
28. push();
29. break;
30. }
31. case 2:
32. {
33. pop();
34. break;
35. }
36. case 3:
37. {
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 14
UNIT – II
38. display();
39. break;
40. }
41. case 4:
42. {
43. printf("Exiting....");
44. break;
45. }
46. default:
47. {
48. printf("Please Enter valid choice ");
49. }
50. };
51. }
52. }
53. void push ()
54. {
55. int val;
56. struct node *ptr = (struct node*)malloc(sizeof(struct node));
57. if(ptr == NULL)
58. {
59. printf("not able to push the element");
60. }
61. else
62. {
63. printf("Enter the value");
64. scanf("%d",&val);
65. if(head==NULL)
66. {
67. ptr->val = val;
68. ptr -> next = NULL;
69. head=ptr;
70. }
71. else
72. {
73. ptr->val = val;
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 15
UNIT – II
74. ptr->next = head;
75. head=ptr;
76.
77. }
78. printf("Item pushed");
79.
80. }
81. }
82.
83. void pop()
84. {
85. int item;
86. struct node *ptr;
87. if (head == NULL)
88. {
89. printf("Underflow");
90. }
91. else
92. {
93. item = head->val;
94. ptr = head;
95. head = head->next;
96. free(ptr);
97. printf("Item popped");
98.
99. }
100. }
101. void display()
102. {
103. int i;
104. struct node *ptr;
105. ptr=head;
106. if(ptr == NULL)
107. {
108. printf("Stack is empty\n");
109. }
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 16
UNIT – II
110. else
111. {
112. printf("Printing Stack elements \n");
113. while(ptr!=NULL)
114. {
115. printf("%d\n",ptr->val);
116. ptr = ptr->next;
117. }
118. }
119. }

Disadvantages of Stack
1. The Insertion and Deletion of the items in the stack can be done only at one end.
2. The element being inserted first has to wait for the longest time to get popped off
from the stack.
3. Only the element at the top of the stack can be deleted at a time.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 17
UNIT – II
APPLICATIONS OF STACK
1. Reversing a String or a number.
2. Expression Conversion.
3. Expression evaluations.
4. Parsing well formatted parenthesis.
5. Recursion
Other Stack application includes:
1. For example, as processor executes a program, when a function call is made, the
called function must know how to return back to the program, so the current
address of program execution is pushed onto a stack. Once the function is finished,
the address that was saved is removed from the stack, and execution of the
program resumes. If a series of function calls occur, the successive return values are
pushed onto the stack in LIFO order so that each function can return back to calling
program. Stacks support recursive function calls in the same manner as
conventional non recursive calls.
2. Stacks are used by compilers in the process of evaluating expressions & generating
machine code. They are also used to store return addresses in a chain of method
calls during execution of a program.
3. Real-time applications.
a) Direct applications.
The direct applications includes as:
 Page-visited history in a Web browser.
 Undo sequence in a text editor.
 Saving local variables when one function calls another and this one
calls another, and so on.
b) Indirect applications
 Auxiliary data structure for algorithms.
 Component of other data structures.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 18
UNIT – II
QUEUES
INTRODUCTION
Queue is a linear data structure in which additions and deletions takes place at
different ends known as the Rear end and front end respectively. The end at which new
elements are added is called the rear, and the end from which elements are deleted is
called the front. A queue is a collection of items organized in a structure with the First-
In-First-Out (FIFO) property.

Definition:
“A queue is a (ordered) collection of items where all insertions are made to the
end of the sequence and all deletions always are made from the beginning of the
sequence”.

CONCEPT OF A QUEUE:

ADD NEW ITEMS REMOVE ITEMS

REAR FRONT

Example: The persons entering and coming out of a Tunnel.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 19
UNIT – II
The operations for a queue are analogous to those for a stack, the substantial
differences being that insertions go at the end of the list, rather than the beginning, and
that traditional terminology for stacks and queues is different. We shall use the
following operations on queues.
1. MAKENULL (Q) makes queue Q an empty list.
2. FRONT (Q) is a function that returns the first element on queue Q. FRONT (Q) can be
written in terms of list operations as RETRIEVE(FIRST(Q), Q).
3. ENQUEUE(x, Q) inserts element x at the end of queue Q. In terms of list operations,
ENQUEUE(x, Q) is INSERT(x, END(Q), Q).
4. DEQUEUE (Q) deletes the first element of Q; that is, DEQUEUE(Q) is
DELETE(FIRST(Q), Q).
5. EMPTY (Q) returns true if and only if Q is an empty queue.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 20
UNIT – II

Fig. 2.19. Implementation of queue commands.

The following code represents the ‘C’ language representation of queue.


struct queue
{
int que [size];
int front;
int rear;
} Q;

Adding and deleting elements in Queue:

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 21
UNIT – II

In the above figure, Join (36) adds a new element to the rear end of the queue
and as the element 36 enters the queue, the rear pointer is shifted to point the end of
the queue (i.e. rear points to element 36.)
In the second case, Leave function deletes the element 12 fro the front end of the
queue. Now since element 12 is deleted, the next element 7 is at the front end of the
queue.

EXAMPLE PROGRAM IN C TO IMPLEMENT QUEUE USING ARRAYS


/*PROGRAM TO IMPLEMENTATION OF QUEUE USING ARRAR*/

#include<conio.h>
#include<stdio.h>
#define qmax 3
void qinsert(int);
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 22
UNIT – II
void qdelete();
void qdisplay();
int Q[qmax],front=0,rear=0,item,ch;
void main()
{
clrscr();
do
{
printf("\n\n\t--QUEUE--OPERATION--\n");
printf("\n\n\t1.INSERT--\n");
printf("\n\n\t2.DELETE\n");
printf("\n\n\t3.DISPLAY\n");
printf("\n\n\t4.EXIT\n");
printf("\n\tEnter Your choice:-\t");
scanf("%d",&ch);
switch(ch)
{
case 1:
qinsert(item);
break;
case 2:
qdelete();
break;
case 3:
qdisplay();
break;
case 4:
exit(0);
break;
default:
printf("\n\n\tINVALID CHOICE??????\n\n");
break;
}
}
while(ch!=4);
getch();
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 23
UNIT – II
}
void qinsert(int item)
{
if(rear==qmax)
{
printf("\n\n\t OVERFLOW!!\n");
}
else
{
printf("\n\n\t Enter the element:-\t");
scanf("%d",&item);
rear=rear+1;
Q[rear]=item;
printf("\n\t Element Inserted!!\n");
}
if(front==0)
{
front=front+1;
}
}
void qdelete()
{
if(front==0)
{
printf("\n\n\tUNDERFLOW!!\n");
}
item=Q[front];
printf("\n\tElement deleted!\n");
if(front==rear)
{
front=0;
rear=0;
}
else
front=front+1;
}
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 24
UNIT – II
void qdisplay()
{
int i;
printf("\n\n\t--QUEUE-ELEMENT--\n\n");
printf("\n\t");
for(i=front;i<=rear;i++)
{
printf("%d\t",Q[i]);
}
}

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 25
UNIT – II
Linked List implementation of Queue
Due to the drawbacks discussed in the previous section of this tutorial, the array
implementation cannot be used for the large scale applications where the queues are
implemented. One of the alternatives of array implementation is linked list
implementation of queue. The storage requirement of linked representation of a queue
with n elements is o(n) while the time requirement for operations is o(1).
In a linked queue, each node of the queue consists of two parts i.e. data part and the link
part. Each element of the queue points to its immediate next element in the memory.
In the linked queue, there are two pointers maintained in the memory i.e. front pointer
and rear pointer. The front pointer contains the address of the starting element of the
queue while the rear pointer contains the address of the last element of the queue.
Insertion and deletions are performed at rear and front end respectively. If front and
rear both are NULL, it indicates that the queue is empty.
The linked representation of queue is shown in the following figure.

Insert operation
The insert operations append the queue by adding an element to the end of the queue.
The new element will be the last element of the queue.
Firstly, allocate the memory for the new node ptr by using the following statement.
Ptr = (struct node *) malloc (sizeof(struct node));
There can be the two scenario of inserting this new node ptr into the linked queue.
In the first scenario, we insert element into an empty queue. In this case, the
condition front = NULL becomes true. Now, the new element will be added as the only
element of the queue and the next pointer of front and rear pointer both, will point to
NULL.
1. ptr -> data = item;

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 26
UNIT – II
2. if(front == NULL)
3. {
4. front = ptr;
5. rear = ptr;
6. front -> next = NULL;
7. rear -> next = NULL;
8. }
In the second case, the queue contains more than one element. The condition front =
NULL becomes false. In this scenario, we need to update the end pointer rear so that the
next pointer of rear will point to the new node ptr. Since, this is a linked queue, hence
we also need to make the rear pointer point to the newly added node ptr. We also need
to make the next pointer of rear point to NULL.
1. rear -> next = ptr;
2. rear = ptr;
3. rear->next = NULL;
In this way, the element is inserted into the queue. The algorithm and the C
implementation is given as follows.
Algorithm
o Step 1: Allocate the space for the new node PTR
o Step 2: SET PTR -> DATA = VAL
o Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT = NULL
ELSE
SET REAR -> NEXT = PTR
SET REAR = PTR
SET REAR -> NEXT = NULL
[END OF IF]
o Step 4: END

C Function
1. void insert(struct node *ptr, int item; )
2. {
3.
4.
5. ptr = (struct node *) malloc (sizeof(struct node));

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 27
UNIT – II
6. if(ptr == NULL)
7. {
8. printf("\nOVERFLOW\n");
9. return;
10. }
11. else
12. {
13. ptr -> data = item;
14. if(front == NULL)
15. {
16. front = ptr;
17. rear = ptr;
18. front -> next = NULL;
19. rear -> next = NULL;
20. }
21. else
22. {
23. rear -> next = ptr;
24. rear = ptr;
25. rear->next = NULL;
26. }
27. }
28. }
Deletion
Deletion operation removes the element that is first inserted among all the queue
elements. Firstly, we need to check either the list is empty or not. The condition front ==
NULL becomes true if the list is empty, in this case , we simply write underflow on the
console and make exit.
Otherwise, we will delete the element that is pointed by the pointer front. For this
purpose, copy the node pointed by the front pointer into the pointer ptr. Now, shift the
front pointer, point to its next node and free the node pointed by the node ptr. This is
done by using the following statements.
1. ptr = front;
2. front = front -> next;
3. free(ptr);

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 28
UNIT – II
The algorithm and C function is given as follows.
Algorithm
o Step 1: IF FRONT = NULL
Write " Underflow "
Go to Step 5
[END OF IF]
o Step 2: SET PTR = FRONT
o Step 3: SET FRONT = FRONT -> NEXT
o Step 4: FREE PTR
o Step 5: END

C Function
1. void delete (struct node *ptr)
2. {
3. if(front == NULL)
4. {
5. printf("\nUNDERFLOW\n");
6. return;
7. }
8. else
9. {
10. ptr = front;
11. front = front -> next;
12. free(ptr);
13. }
14. }

Menu-Driven Program implementing all the operations on Linked Queue


1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. int data;
6. struct node *next;
7. };

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 29
UNIT – II
8. struct node *front;
9. struct node *rear;
10. void insert();
11. void delete();
12. void display();
13. void main ()
14. {
15. int choice;
16. while(choice != 4)
17. {
18. printf("\n*************************Main Menu*****************************\
n");
19. printf("\n===================================================
==============\n");
20. printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n
4.Exit\n");
21. printf("\nEnter your choice ?");
22. scanf("%d",& choice);
23. switch(choice)
24. {
25. case 1:
26. insert();
27. break;
28. case 2:
29. delete();
30. break;
31. case 3:
32. display();
33. break;
34. case 4:
35. exit(0);
36. break;
37. default:
38. printf("\nEnter valid choice??\n");
39. }
40. }
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 30
UNIT – II
41. }
42. void insert()
43. {
44. struct node *ptr;
45. int item;
46.
47. ptr = (struct node *) malloc (sizeof(struct node));
48. if(ptr == NULL)
49. {
50. printf("\nOVERFLOW\n");
51. return;
52. }
53. else
54. {
55. printf("\nEnter value?\n");
56. scanf("%d",&item);
57. ptr -> data = item;
58. if(front == NULL)
59. {
60. front = ptr;
61. rear = ptr;
62. front -> next = NULL;
63. rear -> next = NULL;
64. }
65. else
66. {
67. rear -> next = ptr;
68. rear = ptr;
69. rear->next = NULL;
70. }
71. }
72. }
73. void delete ()
74. {
75. struct node *ptr;
76. if(front == NULL)
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 31
UNIT – II
77. {
78. printf("\nUNDERFLOW\n");
79. return;
80. }
81. else
82. {
83. ptr = front;
84. front = front -> next;
85. free(ptr);
86. }
87. }
88. void display()
89. {
90. struct node *ptr;
91. ptr = front;
92. if(front == NULL)
93. {
94. printf("\nEmpty queue\n");
95. }
96. else
97. { printf("\nprinting values .....\n");
98. while(ptr != NULL)
99. {
100. printf("\n%d\n",ptr -> data);
101. ptr = ptr -> next;
102. }
103. }
104. }

Output:

***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Enter your choice ?1

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 32
UNIT – II

Enter value?
123
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Enter your choice ?1
Enter value?
90
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Enter your choice ?3
printing values .....

123
90
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Enter your choice ?2
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice ?3


printing values .....
90
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit

Enter your choice?4

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 33
UNIT – II

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 34
UNIT – II

Applications of Queue
The queue is also very general-purpose container and it can be used in various
applications. The simplest application of queue is where we need a data storage where
data items are waiting for further processing and processed in the in the order “they
came in”.
 Queues are frequently used in operating systems and networking software
modules.
 Job-Scheduling.
 Processor queue.
 Network router queues of outgoing packets, etc.
 Maintain chronological order of print jobs or transactions while waiting for one
to complete.
 Simulate retail or bank operations such as withdrawing cash from an ATM
machine.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 35
UNIT – II
Disadvantages of Queue
1. Only the elements at the front end of the queue can be deleted.
2. Insertion of the elements can be done at the rear end only.
3. Memory space is not effectively used in Array Implementation. There will be
empty spaces created on the Front side on deletion. But, the Linear Queue is
considered Full when the Rear reaches the last position. As a result, the empty
spaces in the Front are not utilized until the queue becomes empty.

Overcome disadvantage of linear queue:


To overcome disadvantage of linear queue, circular queue is use.
We can solve this problem by joining the front and rear end of a queue to make
the queue as a circular queue.
Circular queue is a linear data structure.
It follows FIFO principle.
In circular queue the last node is connected back to the first node to make a
circle.

CONCEPT OF CIRCULAR QUEUE


As the name suggests, this queue is circular, it looks like this.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 36
UNIT – II
Fig.: Circular Queue
In this Circular queue, once the queue is full, the “first” element of the queue
becomes the “rear” most element of the queue. Initially when the queue is empty ”front”
and ”rear” values are 0 and -1. Queue has got null values to all its elements. Every time
when we add an element to the queue, the ”rear” value increments by one till the time it
reaches the upper limit of the queue after which it starts all over again from 0. Here the
condition front>rear wont work

For an element to be enqueued the algorithm is,


void addq(element x)
{ /* add an element x to the queue */
rear = (rear+1) % MAX_QUEUE_SIZE;
if(front==rear)
queueFull(); /* print error and exit. */
queue[rear] = x;
}

For an element to be dequeued the algorithm is,


element deleteq()
{ /* remove front element from the queue */
element x;
if(front==rear)
return queueEmpty(); /* Return an error. */
front = (front+1) % MAX_QUEUE_SIZE;
return queue[front];
}

There is a formula which has to be applied for setting the front and rear pointers,
for a circular queue.
REAR + (REAR + 1) % SIZE OF QUEUE
FRONT + (FRONT + 1) % SIZE OF QUEUE

/*Program to implementation of CIRCULAR QUEUE using ARRAY*/

#include<conio.h>
#include<stdio.h>
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 37
UNIT – II
#define qmax 3
void qinsert();
void qdelete();
void qdisplay();
int Q[qmax],front=0,rear=0,item,ch;
void main()
{
clrscr();
do
{
printf("\ncircular queue\n");
printf("1.inserting\n");
printf("2.deleting\n");
printf("3.display\n");
printf("4.exit\n");
printf("Enter Your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:

qinsert();
break;
case 2:
qdelete();
break;
case 3:
qdisplay();
break;
case 4:
exit(0);
break;
default:
printf("\ninvalid chice");
break;
}
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 38
UNIT – II
}
while(ch!=4);
getch();
}
void qinsert()
{
if((front==1 && rear==qmax)||(front==rear+1))
{
printf("\noverflow");
}
else
{
if(front==0)
{
front=1;
rear=1;
}
else if(rear==qmax)
{
rear=1;
}
else
{
rear=rear+1;
}
printf("Enter the element:\n");
scanf("%d",&item);
Q[rear]=item;

printf("\nElement Inserted");
}
}
void qdelete()
{
if(front==0)
{
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 39
UNIT – II
printf("\nUnderflow");
}
else
{
item=Q[front];
if(front==rear)
{
front=0;
rear=0;
}
else if(front==qmax)
{
front=1;
}
else
{
front=front+1;
}
}
}

void qdisplay()
{
int i;
if(front==0)
{
printf("\n Underflow");
}
else if(rear<front)
{
for(i=1;i<=rear;i++)
{
printf("%d\t",Q[i]);
}
for(i=front;i<=qmax;i++)
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 40
UNIT – II
{
printf("%d\t",Q[i]);
}
}
else
{
for(i=front;i<=rear;i++)
{
printf("%d\t",Q[i]);
}
}

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 41
UNIT – II
PRIORITY QUEUE
It is a special type of queue in which the elements are arranged based on the priority. It
is a special type of queue data structure in which every element has a priority
associated with it. Suppose some elements occur with the same priority, they will be
arranged according to the FIFO principle. The representation of priority queue is shown
in the below image -

“A Queue in which we are able to insert or remove items from any position based
on some property (such as priority of the task to be processed) is often referred
to as priority queue.”
A priority can be conceptualized as a series of queues representing situations in
which it knows what priorities are associated with queue items.

Characteristics of a Priority queue


A priority queue is an extension of a queue that contains the following characteristics:
Every element in a priority queue has some priority associated with it.
An element with the higher priority will be deleted before the deletion of the
lesser priority.
If two elements in a priority queue have the same priority, they will be arranged
using the FIFO principle.

Insertion in priority queue takes place based on the arrival, while deletion in the
priority queue occurs based on the priority. Priority queue is mainly used to implement
the CPU scheduling algorithms.

Let's understand the priority queue through an example.

We have a priority queue that contains the following values:


S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 42
UNIT – II

1, 3, 4, 8, 14, 22

All the values are arranged in ascending order. Now, we will observe how the priority
queue will look after performing the following operations:

poll(): This function will remove the highest priority element from the priority
queue. In the above priority queue, the '1' element has the highest priority, so it
will be removed from the priority queue.
add(2): This function will insert '2' element in a priority queue. As 2 is the
smallest element among all the numbers so it will obtain the highest priority.
poll(): It will remove '2' element from the priority queue as it has the highest
priority queue.
add(5): It will insert 5 element after 4 as 5 is larger than 4 and lesser than 8, so it
will obtain the third highest priority in a priority queue.

Types of Priority Queue


There are two types of priority queue:
o Ascending order priority queue: In ascending order priority queue, a lower
priority number is given as a higher priority in a priority. For example, we take
the numbers from 1 to 5 arranged in an ascending order like 1,2,3,4,5; therefore,
the smallest number, i.e., 1 is given as the highest priority in a priority queue.

o Descending order priority queue: In descending order priority queue, a higher


priority number is given as a higher priority in a priority. For example, we take
the numbers from 1 to 5 arranged in descending order like 5, 4, 3, 2, 1; therefore,

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 43
UNIT – II
the largest number, i.e., 5 is given as the highest priority in a priority queue.

Representation of priority queue


Now, we will see how to represent the priority queue through a one-way list.
We will create the priority queue by using the list given below in which INFO list
contains the data elements, PRN list contains the priority numbers of each data element
available in the INFO list, and LINK basically contains the address of the next node.

Let's create the priority queue step by step.


In the case of priority queue, lower priority number is considered the higher
priority, i.e., lower priority number = higher priority.
Step 1: In the list, lower priority number is 1, whose data value is 333, so it will be
inserted in the list as shown in the below diagram:
Step 2: After inserting 333, priority number 2 is having a higher priority, and data
values associated with this priority are 222 and 111. So, this data will be inserted based
on the FIFO principle; therefore 222 will be added first and then 111.
Step 3: After inserting the elements of priority 2, the next higher priority number is 4
and data elements associated with 4 priority numbers are 444, 555, 777. In this case,

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 44
UNIT – II
elements would be inserted based on the FIFO principle; therefore, 444 will be added
first, then 555, and then 777.
Step 4: After inserting the elements of priority 4, the next higher priority number is 5,
and the value associated with priority 5 is 666, so it will be inserted at the end of the
queue.

Implementation of Priority Queue


The priority queue can be implemented in four ways that include arrays, linked list,
heap data structure and binary search tree. The heap data structure is the most efficient
way of implementing the priority queue, so we will implement the priority queue using
a heap data structure in this topic. Now, first we understand the reason why heap is the
most efficient way among all the other data structures.
Analysis of complexities using different implementations

Implementation add Remove peek

Linked list O(1) O(n) O(n)

Binary heap O(logn) O(logn) O(1)

Binary search tree O(logn) O(logn) O(1)

Applications of Priority Queues:

The following are the applications of the priority queue:


o It is used in the Dijkstra's shortest path algorithm.
o It is used in prim's algorithm
o It is used in data compression techniques like Huffman code.
o It is used in heap sort.
o It is also used in operating system like priority scheduling, load balancing and
interrupt handling.

Advantages of Priority Queue:


S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 45
UNIT – II
It helps to access the elements in a faster way. This is because elements in a
priority queue are ordered by priority, one can easily retrieve the highest
priority element without having to search through the entire queue.
The ordering of elements in a Priority Queue is done dynamically. Elements in a
priority queue can have their priority values updated, which allows the queue to
dynamically reorder itself as priorities change.
Efficient algorithms can be implemented. Priority queues are used in many
algorithms to improve their efficiency, such as Dijkstra’s algorithm for finding
the shortest path in a graph and the A* search algorithm for pathfinding.
Included in real-time systems. This is because priority queues allow you to
quickly retrieve the highest priority element, they are often used in real-time
systems where time is of the essence.
Disadvantages of Priority Queue:
High complexity. Priority queues are more complex than simple data structures
like arrays and linked lists, and may be more difficult to implement and maintain.
High consumption of memory. Storing the priority value for each element in a
priority queue can take up additional memory, which may be a concern in
systems with limited resources.
It is not always the most efficient data structure. In some cases, other data
structures like heaps or binary search trees may be more efficient for certain
operations, such as finding the minimum or maximum element in the queue.
At times it is less predictable:. This is because the order of elements in a priority
queue is determined by their priority values, the order in which elements are
retrieved may be less predictable than with other data structures like stacks or
queues, which follow a first-in, first-out (FIFO) or last-in, first-out (LIFO) order.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 46
UNIT – II
APPLICATIONS OF STACK
I.POLISH NOTATION
The Polish mathematician JAN ŁUKASIEWICZ made the observation that, by
writing all operators either before their operands or after them, it is not necessary to
keep track of priorities, of parentheses bracketing expressions, or to make repeated
scans to evaluate an expression.
An Expression is a string of operands and operators. Operands are some numeric
values and operator are of two types either unary or binary. There are three types of
expressions.
1. Infix Expression.
2. Postfix Expression.
3. Prefix Expression.
INFIX, POSTFIX & PREFIX EXPRESSIONS
Infix, Postfix and Prefix notations are three different but equivalent ways of
writing expressions. It is easiest to demonstrate the differences by looking at examples
of operators that take two operands.

Infix notation: X + Y
Operators are written in-between their operands. This is the usual way we write
expressions. An expression such as A * (B + C) / D is usually taken to mean something
like: "First add B and C together, then multiply the result by A, then divide by D to give
the final answer."

Infix notation needs extra information to make the order of evaluation of the
operators clear: rules built into the language about operator precedence and
associativity, and brackets ( ) to allow users to override these rules. For example, the
usual rules for associativity say that we perform operations from left to right, so the
multiplication by A is assumed to come before the division by D. Similarly, the usual
rules for precedence say that we perform multiplication and division before we perform
addition and subtraction.

Postfix notation (also known as "Reverse Polish notation"): X Y +


Operators are written after their operands. The infix expression given above is
equivalent to A B C + * D /. The order of evaluation of operators is always left-to-right,
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 47
UNIT – II
and brackets cannot be used to change this order. Because the "+" is to the left of the "*"
in the example above, the addition must be performed before the multiplication.
Operators act on values immediately to the left of them. For example, the "+" above uses
the "B" and "C". We can add (totally unnecessary) brackets to make this explicit:
((A (B C +) *) D /)
Thus, the "*" uses the two values immediately preceding: "A", and the result of the
addition. Similarly, the "/" uses the result of the multiplication and the "D".

Prefix notation (also known as "Polish notation"): + X Y


Operators are written before their operands. The expressions given above are
equivalent to / * A + B C D. As for Postfix, operators are evaluated left-to-right and
brackets are superfluous. Operators act on the two nearest values on the right. I have
again added (totally unnecessary) brackets to make this clear:

(/ (* A (+ B C)) D)
Although Prefix "operators are evaluated left-to-right", they use values to their
right, and if these values themselves involve computations then this changes the order
that the operators have to be evaluated in. In the example above, although the division
is the first operator on the left, it acts on the result of the multiplication, and so the
multiplication has to happen before the division (and similarly the addition has to
happen before the multiplication).
Because Postfix operators use values to their left, any values involving
computations will already have been calculated as we go left-to-right, and so the order
of evaluation of the operators is not disrupted in the same way as in Prefix expressions.
In all three versions, the operands occur in the same order, and just the
operators have to be moved to keep the meaning correct. (This is particularly important
for asymmetric operators like subtraction and division: A - B does not mean the same as
B - A; the former is equivalent to A B - or - A B, the latter to B A - or - B A).

PRIORITIES OF OPERATORS

The quadratic formula:

Order of doing operators:

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 48
UNIT – II

Priorities of operators: Table

CONVERSION FROM INFIX TO POSTFIX EXPRESSION:


There are certain rules which have to be followed while converting infix
expression to postfix form.
1. The expression is to be read from left to right.
2. Read one character at a time from infix expression.
3. Make use of stack to store the operators.
4. There should not be any parenthesis in the prefix form.

ALGORITHM FOR CONVERSION FROM INFIX TO POSTFIX EXPRESSION


1. Read the expression from left to right.
2. If the input symbol read is ‘(’ then push it on to the stack.
3. If the input symbol read is operand then place it in postfix expression.
4. If the input symbol read is operator then:
a. Check the precedence of the operator which is in stack has greater
precedence than the precedence of the operator read. If so then remove
that symbol from the stack and place it in the postfix expression. Repeat
step 4(a) till you get the operator in the stack has greater precedence than
the operator being read.
b. Otherwise push the operator being read onto the stack.
5. If the input symbol read is ‘)’ then pop all the operators from the stack, place
them in postfix expression till the opening parenthesis is not popped. The ‘(’
should not be placed in the postfix expression.
6. Finally print the postfix expression.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 49
UNIT – II

Example 1:

Infix Postfix Prefix Notes


multiply A and B,
A*B+C/D AB*CD/+ +*AB/CD divide C by D,
add the results
add B and C,
A * (B + C) / D ABC+*D/ /*A+BCD multiply by A,
divide by D
divide C by D,
A * (B + C / D) ABCD/+* *A+B/CD add B,
multiply by A
CONVERTING BETWEEN THESE NOTATIONS
The most straightforward method is to start by inserting all the implicit brackets
that show the order of evaluation e.g.:

Infix Postfix Prefix

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

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

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

You can convert directly between these bracketed forms simply by moving the
operator within the brackets e.g. (X + Y) or (X Y +) or (+ X Y). Repeat this for all the
operators in an expression, and finally remove any superfluous brackets.

Example 2: Inter Conversions between infix, prefix and postfix.

Infix Prefix Postfix

(A + B)/D /+ABD AB+D/

(A + B)/(D + E) /+AB+DE AB+DE+/

(A - B/C + E)/(A+B) /+-A/BCE+AB ABC/-E+AB+/

B2 - 4*A*C -^B2**4AC B2^4A*C*-

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 50
UNIT – II
Use of stack by Function call & Recursive call:
The function call requires a special data structure called “stack”. But a call to a
function can be of two types.
1. Recursive function call.
2. Non-Recursive function call / Iterative call.

RECURSIVE FUNCTION CALL


DEFINATION: - “Recursion is a programming technique in which the function calls itself
repeatedly for some input.”
Example:
1. Computing factorial of a number.
5! = 5 * 4 * 3 * 2 * 1 = 120.
There are 2 ways to represent the algorithms for computing the factorial of the number.
1. Iterative method.
2. Recursive method.

Algorithm for computing factorial of a number using Iterative method:


1. Prod = 1;
2. x = n;
3. while(x>0)
4. {
5. Prod = prod *x;
6. x--;
7. }
8. Return(prod)
Such an algorithm is called as an iterative algorithm because it calls explicit
repetitions of some process (Multiplication & decrementing x) until certain condition is
met (x>0).
The definition of factorial is:
n! =1 if n==0
Otherwise, n! = n*(n-1)*(n-2)*………..*1 if n>0.

Such an algorithm is called as an recursive algorithm because it the same


procedure of multiplication is followed again and again.

Algorithm for computing factorial of a number using Recursive method:


S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 51
UNIT – II
1. if(n==0)
2. fact =1;
3. else
4. {
5. x = n-1;
6. y = value of x!;
7. fact = n*y;
8. }

COMPARISON BETWEEN ITERATION & RECURSION


Sr.
ITERATION RECURSION
no
It is a process of executing certain set of It is a process of executing certain set of
1 instructions repeatedly without calling instructions repeatedly calling the self
the self function. function repeatedly.
2 More efficient. Less Efficient.
3 Memory utilization is less. Memory utilization is more.
4 Simple to implement. Complex to implement.
5 More lines of code in iteration. Compact code.

TOWERS OF HANOI
INTRODUCTION
The Tower of Hanoi, a puzzle invented by French mathematician ´Edouard Lucas
in 1883, consists of three vertical pegs and some number n of disks, all with a hole in the
center that allows them to be stacked on the pegs. The disks are all of different radii, and
we imagine that they are numbered 1 through n in increasing order of size. They are
initially stacked in order on one of the pegs, with disk n on the bottom and 1 on the top.
The object is to transport this tower from the starting peg to a destination peg, moving
one disk at a time, and always placing a disk on either an empty peg or on a larger disk.
The third peg is used to temporarily hold disks during the process.

The Towers of Hanoi

In the Towers of Hanoi problem, there are three posts and seven disks of
different sizes. Each disk has a hole through the center so that it fits on a post. At the

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 52
UNIT – II
start, all seven disks are on post #1 as shown below. The disks are arranged by size so
that the smallest is on top and the largest is on the bottom. The goal is to end up with all
seven disks in the same order, but on a different post. This is not trivial because of two
restrictions. First, the only permitted action is removing the top disk from a post and
dropping it onto another post. Second, a larger disk can never lie above a smaller disk
on any post. (These rules imply, for example, that it is no fair to pick up the whole stack
of disks at once and then to drop them all on another post!)

One approach to this problem is to consider a simpler variant with only three
disks. We can quickly exhaust the possibilities of this simpler puzzle and find a 7 move
solution such as the one shown below. (The disks on each post are indicated by the
numbers immediately to the right. Larger numbers correspond to larger disks.)

FINDING A RECURRENCE

The Towers of Hanoi problem can be solved recursively as follows. Let Tn be


the minimum number of steps needed to move an n disk tower from one post to
another. For example, a bit of experimentation shows that T1 =1 and T2 =3. For 3 disks,
the solution given above proves that T3≤ 7. We can generalize the approach used for 3
disks to the following recursive algorithm for n disks.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 53
UNIT – II
Step 1: Apply this strategy recursively to move the top n - 1 disk from the first post to
the third post. This can be done in Tn-1 steps.

Step 2: Move the largest disk from the first post to the second post. This requires just 1
step.

Step 3: Recursively move the n - 1 disk on the third post over to the second post. Again,
Tn-1 steps are required.

EXAMPLE:
Consider a problem with 3 disks as A, B and C and 3 pegs as 1, 2 and 3. The
following figure represents the initial and final state of the problem.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 54
UNIT – II

There are 3 pegs ‘from’, ‘using ‘and ‘to’. Some disks of different sizes are given
which can slide onto any peg. Initially all of those are in ‘from’ peg in order of size with
largest disk at the bottom and smallest disk at the top. We have to move all the disks
from ‘from’ peg to ‘to’ peg. At the end,’ to’ peg will have disks in the same order of size.
There are some rules:
1) Only one disk can be moved from one peg to another peg at a time.
2) A disk can be placed only on top of a larger one.
3) A disk can be moved from top only.

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 55
UNIT – II

Time Complexity:
Let the time required for n disks is T(n). There are 2 recursive call for n-1 disks
and one constant time operation to move a disk from ‘from’ peg to ‘to’ peg. Let it be k
1.

Therefore,
T(n) = 2 T(n-1) + k
1

T(0) = k , a constant.
2

T(1) = 2 k + k
2 1

T(2) = 4 k + 2k + k
2 1 1

T(2) = 8 k + 4k + 2k + k
2 1 1 1

n
Coefficient of k1 =2
n
Coefficient of k2 =2 -1
n n
Time complexity is O(2 ) or O(a ) where a is a constant greater than 1. So it has
exponential time complexity. For single increase in problem size the time required is
double the previous one. This is computationally very expensive. Most of the recursive
programs take exponential time that is why it is very hard to write them iteratively.

Space Complexity:
Space for parameter for each call is independent of n i.e., constant. Let it be k.
nd st
When we do the 2 recursive call 1 recursive call is over. So, we can reuse the space of
st nd
1 call for 2 call.
Hence,
T(n) = T(n-1) + k
T(0) = k
T(1) = 2k
T(2) = 3k
T(3) = 4k
So the space complexity is O(n). Here time complexity is exponential but space
complexity is linear. Often there is a trade off between time and space complexity.

************ END OF UNIT 2 NOTES ************

S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 56

You might also like