0% found this document useful (0 votes)
25 views135 pages

DS Unit 1

The document discusses the importance of data structures and algorithms in computer science, emphasizing their role in organizing, storing, and processing data efficiently. It covers fundamental concepts, types of data structures, operations performed on them, and the advantages of using Abstract Data Types (ADTs). Additionally, it explains static and dynamic data structures, their characteristics, and various applications in computing.
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)
25 views135 pages

DS Unit 1

The document discusses the importance of data structures and algorithms in computer science, emphasizing their role in organizing, storing, and processing data efficiently. It covers fundamental concepts, types of data structures, operations performed on them, and the advantages of using Abstract Data Types (ADTs). Additionally, it explains static and dynamic data structures, their characteristics, and various applications in computing.
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/ 135

UNIT-I

Why Learn Data Structure?

Data structure and algorithms are two of the most important


aspects of computer science.
Data structures allow us to organize and store data, while
algorithms allow us to process that data in a meaningful way.
Learning data structure and algorithms will help you become
a better programmer. You will be able to write code that is
more efficient and more reliable.
You will also be able to solve problems more quickly and
more effectively.
7
What is a Data structure?

• Data Structures are a way to organize information in a


computer's memory.
• Data Structures facilitates storage and retrieval of information
• A Data Structures are an organized way of arranging data so
that it can be easily operated on, saved and abstracted as and
when required.

Example:
1. Our Name is a Data Structures which comprises of First Name,
Middle Name and Last Name
2. The Date is a Data Structures DD-MM-YYYY
3. IFSC code of Bank
4. Passport Number
Factors that are needed in the selection of Data
Structures

Choosing an appropriate Data Structure is very important


and its gives faster execution.
Factors that are needed in the selection of Data Structures
are
• What kind of Data will it save?
• How will that data be used?
• Where data should be kept?
• How can the data be organized in a cost effective
manner?
• Based on Memory and storage Management.
Need of Data Structure

• As applications are becoming more complex and the amount


of data is increasing day by day, which may cause problems
with processing speed, searching data, handling multiple
requests etc.
• Data structure provides a way of organizing, managing, and
storing data efficiently. With the help of data structure, the
data items can be traversed easily.
• Data structure provides efficiency, reusability and
abstraction.
• It plays an important role in enhancing the performance of a
program because the main function of the program is to
store and retrieve the user’s data as fast as possible.
Fundamental Concepts:
 Data:
A collection of facts, concepts, figures, observations,
occurrences or instructions in a formalized manner.
 Information:
The meaning that is currently assigned to data by means
of the conventions applied to those data(i.e. processed data)
 Record:
Collection of related fields.
 Data type:
Set of elements that share common set of properties
used to solve a program.

11
Fundamental Concepts:

 Algorithm:
A Logical Module design
 Handle specific problem
 Relative to particular data structure
 Properties Of An Effective Algorithm:
Algorithm should be
 Concise and Compact
 Effective Memory Utilization
 Less Time Consuming
 Clear and Definite
 Efficient
12
Data Structures

Characteristics of data structures:


 Depicts the logical representation of data in computer
memory.
 Represents the logical relationship between the various
data elements.
 Helps in efficient manipulation of stored data elements.
 Allows the programs to process the data in an efficient
manner.

13
Applications Of Data Structures

 Operating System
 Compiler Design
 Database Management System
 Expert Systems
 Network Analysis

14
Dynamic aspects of operations on data

What is a Static Data structure?


In Static data structure the size of the structure is fixed.
The content of the data structure can be modified but
without changing the memory space allocated to it.

15
Dynamic aspects of operations on data

What is Dynamic Data Structure?

In Dynamic data structure the size of the structure is not


fixed and can be modified during the operations
performed on it. Dynamic data structures are designed to
facilitate change of data structures in the run time.

Example of Dynamic Data Structures: Linked List

16
Dynamic aspects of operations on data

Static Data
Aspect Dynamic Data Structure
Structure
Memory is
Memory allocation allocated at Memory is allocated at run-time
compile-time
Size is fixed and
Size cannot be modified Size can be modified during runtime
Memory utilization Memory utilization is efficient as
Memory utilization
may be inefficient memory can be reused
Access time is Access time may be slower due to
Access
faster as it is fixed indexing and pointer usage
Arrays, Stacks,
Lists, Trees (with variable size), Hash
Examples Queues, Trees
tables 17
(with fixed size)
Characteristics of Data

Volume:
The amount of data.
Impacts storage and processing requirements.
Velocity:
The speed at which data is generated and processed.
High velocity data requires real-time processing capabilities.
Variety:
The different types and sources of data.
Includes structured, semi-structured, and unstructured data.
Veracity:
The quality and accuracy of data.
Value:
The usefulness of the data for decision-making.
Data should be relevant and actionable.

18
Creation, Manipulation and Operations on data

• Traversing
• Insertion
• Deletion
• Search
• Sorting
• Merging
Traversing
Every data structure contains the set of data elements.
Traversing operation on Data Structure means visiting each element of the
data structure.
After traversing the data structure we can perform a specific task on those
data elements.
For Example If we need to calculate the average of the marks obtained by
a student in 6 different subject, we need to traverse the complete array of
marks and calculate the total sum, then we will divide that sum by the
number of subjects i.e. 6, in order to find the average.
19
Creation, Manipulation and Operations on data

Insertion
•Insertion operation in Data Structure means represents the
adding new elements to the existing data structure at a specific
location.
•If the size of data structure is n then we can only insert (n-1)
data elements into it.
Deletion
•The process of removing an element from the existing data
structure is called Deletion.
•We can delete an element from the data structure at any
random location.
•If we try to delete an element from an empty data structure
then underflow occurs.
20
Creation, Manipulation and Operations on data

Searching
The process of finding the location of an existing element within a data
structure is called Searching.
Linear Search and Binary Search are two most popular searching
algorithms.
Sorting
The process of arranging the data structure elements in a specific order
either descending or ascending is known as Sorting.
There are many algorithms that can be used to perform sorting, for
example, insertion sort, selection sort, bubble sort, etc.
Merging
When two lists List A and List B of size M and N respectively, of similar
type of elements, clubbed or joined to produce the third list, List C of
size (M+N), then this process is called merging.

21
Operations Of Data Structures

1.Traversal
2.Search
3.Insertion
4.Deletion
5.Sorting
6.Merging

22
Classification of Data Structures

23
Classification of Data Structures

Primary Data Structures/Primitive Data Structures:


Primitive data structures include all the fundamental data
structures
Directly manipulated by machine-level instructions.
Some of the common primitive data structures include integer,
character, real, Boolean etc
Secondary Data Structures/Non Primitive Data Structures:
 Non primitive data structures, refer to all data structures that
are derived from one or more primitive data structures.
 The objective of creating non-primitive data structures is to
form sets of homogeneous or heterogeneous data elements.

24
Classification of Data Structures

Linear Data Structures:


 Linear data structures are data structures in which, all the
data elements are arranged in linear or sequential
fashion.
 Examples of data structures include arrays, stacks,
queues, linked lists, etc.
Non Linear Structures:
 A Non-linear data structures could arrange data elements
in a hierarchical fashion.
 Examples of non-linear data structures are trees and
graphs.
25
26
Abstract Data Type(ADT)

Definition Of ADT:
 An Abstract Data Type (ADT) is defined as a mathematical
model with a collection of operations defined on that model.
Set of integers, together with the operations of union,
intersection and set difference form a example of an ADT.
 An ADT consists of data together with functions that operate
on that data.
 An ADT is a set of objects together with a set of operations.
 An ADT is an extension of Modular Design
 Example:

Lists,sets,graphs, stacksare examplesof ADT along with their operations

27
Why ADT?
 Modularity
Divide program into small functions
Easy to debug and maintain
Easy to modify
Group work
 Reuse
Do some operations onlyonce
 Easy to changethe implementation

28
Advantages/Benefits of ADT:

1.Modularity
2.Reuse
3.Code is easier to understand
4.Implementation of ADTs can be changed
without requiring changes to the program
that uses the ADTs.

29
Advantages of Modularity

1.Modules can be compiled separately which


makes debugging process easier.
2. Several modules can be implemented and
executed simultaneously.
3. Easily enhanced

30
The ListADT
The List is an
Ordered sequence of data items
A1,A2, A3, …,AN isa list of sizeN
Sizeof an empty list is 0
Ai+1 succeeds Ai

Ai-1 preceeds Ai
Position ofAi is i
First elementisA1 called “head”
Last element isAN called “tail”

31
Various operations performed on List

 Insert (X, 5)- Insert the element X after the position 5.

 Delete (X) - The element X is deleted

 Find (X) - Returns the position of X.

 Next (i) - Returns the position of its successor element i+1.

 Previous (i) - Returns the position of its predecessor i-1.

 Print list - Contents of the list is displayed.

 Makeempty- Makes the list empty.

32
List– AnExample

 The elements of a listare 34, 12, 52, 16, 12


 Insert (20, 4) -> 34, 12, 52, 16,20, 12
 Delete (52) -> 34, 12, 16, 20,12
 Find (16) -> 3
 FindKth(3) -> 16

33
Implementation of List ADT

 Array Implementation

 Linked List Implementation

34
Array
 Arrays are defined as the collection of similar types of data items
stored at contiguous memory locations.
 It is one of the simplest data structures where each data element
can be randomly accessed by using its index number.
 Array is a static data structure i.e., the memory should be
allocated in advance and the size is fixed. This will waste the
memory space when used space is less than the allocated space.
 Element − Each item stored in an array is called an element.
 Index − Each location of an element in an array has a numerical
index, which is used to identify the element.

35
Need for Array

Arrays are useful because -


•Sorting and searching a value in an array is easier.
•Arrays are best to process multiple values quickly and easily.
•Arrays are good for storing multiple values in a single variable
•Storing data for processing
•Implementing data structures such as stacks and queues
•Representing data in tables and matrices 36
Array Representation

37
Declaration of Array

 int arr[5];
 char arr[10];
 float arr[20];

38
Initialization of Array

 You can initialize an array in arr[2]=3;


four different ways: arr[3]=4;
Method 1: arr[4]=5;
int a[6] = {2, 3, 5, 7,
11, 13}; Method 4:
Method 2: int n;
int arr[]= {2, 3, 5, 7, scanf(“%d”,&n);
11}; int arr[n];
Method 3: for(int i=0;i<5;i++)
int arr[5]; {
arr[0]=1; scanf(“%d”,&arr[i]);
arr[1]=2; } 39
Memory representation of Array

In an array, all the elements are stored in contiguous memory locations.


So, if we initialize an array

40
Types of Array

There are two main types of arrays:


One-dimensional arrays: These arrays store a single row of elements.
Multidimensional arrays: These arrays store multiple rows of elements.

41
Basic Operations in Arrays

•Traverse − print all the array elements one by one.


•Insertion − Adds an element at the given index.
•Deletion − Deletes an element at the given index.
•Search − Searches an element using the given
index or by the value.
•Update − Updates an element at the given index.
•Display − Displays the contents of the array.

42
Print ListOperation

int Arr[5] = {19,68,12,45,72};


for (int i=0;i<5;i++)
{
printf("%d", Arr[i]);
}

43
Traversal operation
The array elements are traversed using this operation. It sequentially
prints each element of the array.

#include <stdio.h>
void main()
{
int Arr[5] = {18, 30, 15, 70, 12};
int i;
printf("Elements of the array are:\n");
for(i = 0; i<5; i++) {
printf("%d”, Arr[i]);
}
}
44
Insertion operation

This operation is performed to insert one or more


elements into the array. As per the requirements,
an element can be added at the beginning, end, or
at any index of the array.

45
Insertion operation
#include <stdio.h> // Shift the elements after the
void main() insertion position to the right
{ for (i = size - 1; i >= pos-1; i--)
int a[50],i,size, pos, item; {
printf("Enter the size of the array: "); a[i+1] = a[i];
scanf("%d", &size); }
printf("Enter the elements of the // Insert the new element at the
array:"); desired position
for ( i = 0; i < size; i++) a[pos-1] = item;
{
scanf("%d", &a[i]); size++;
}
printf("Elements of the array before printf(" Elements of the array after
insertion:\n"); insertion :");
for(i = 0; i<5; i++) { for (i = 0; i < size; i++)
printf("%d”, a[i]); {
} printf("%d", a[i]);
printf("Enter the position and value }
of the new element to be inserted: "); getch(); 46
scanf("%d%d", &pos, &item); }
Insertion operation

47
Deletion operation
include <stdio.h> for (i = position-1; i < size-1; i++)
#include <conio.h> {
void main() a[i] = a[i+1];
{ }
int a[100], position, i, size; printf("Final array is");

printf("Enter the number of for (i = 0; i < size-1; i++)


elements in array"); {
scanf("%d", &size); printf("%d", a[i]);
}
printf("Enter %d elements", n); }
for (i = 0; i < size; i++) getch();
{ }
scanf("%d", &a[i]);
}
printf("Enter the location where you
wish to delete element");
scanf("%d", &position);
48
Deletion operation

49
Operations Of List

1.IsEmpty(LIST)
2.IsFull(LIST)
3.Insert Element to End of the LIST.
4.Delete Element from End of the LIST.
5.Insert Element to front of the LIST.
6.Delete Element from front of the LIST.
7.Insert Element to nth Position of the LIST.
8.Delete Element from nth Position of the LIST.
9.Search Element in the LIST.
10.Print the Elements in the LIST.

50
Advantage and Disadvantage Of Array
Implementation
Advantages of array implementation:
 The elements are faster to access using random access
 Searching an element is easier
Limitation of array implementation
 An array store its nodes in consecutive memory locations.
 The number of elements in the array is fixed and it is not possible to change the
number of elements .
 Insertion and deletion operation in array are expensive. Since insertion is
performed by pushing the entire array one position down and deletion is
performed by shifting the entire array one position up.
Applications of arrays
 Arrays are particularly used in programs that require storing large collection of
similar type data elements.

51
Linked List Implementation

DATA NEXT
ELEMENT POINTER

NODE
 Consist of series of nodes.
 Each node contains Element and pointer
 Pointer points or links to the successor node
 Pointer of last node points to NULL.
700 1000 800

10 20 30 40
500 700 1000 800
52
Type Of Linked List

 Singly Linked List


 Doubly Linked List
 Circularly Linked List

53
Singly Linked List

Definition:
Each Node contains data field and only one
link field that link is pointing to the successor node.
700 1000 800

23 13 45 9

550 700 1000 800


Linked List
Header L

700 1000 800


23 13 45 9
550 700 1000 800
54
Declaration For Linked List

struct Node;
int IsEmpty(List L);
int IsLast(List L);
position Find(int X,List L);
position FindPrevious(int X,List L);
position FindNext(int X,List L);
void insert(int X,List L,Position P);
void Delete(int X,List L);
void DeleteList(List L);

55
Creating a Node:

struct Node
{
int element;
struct node* Next;
};
DATA NEXT

56
Routine to check whether the list is
empty or not:
int IsEmpty(List L)
{
if(L->Next = = NULL)
return (1);
}

int IsEmpty(List L)
{
if(L->Next = = NULL)
{ return (1); Header L 10

}
return (0);
57
}
Routine to check whether the current
position is last or not:

int IsLast(position P,List L)


{
if(P->Next = = NULL)
{
return (1);
}
return (0);
} L 10 20 25
P

58
Find Routine

position Find(int X, List L)


{
position P;
P=L Next;
while(P! = NULL && P->Element! = X)
P = P Next;
return P;
}

FIND (10)
L 10 20 25

P
Routine To Insert An Element In The List

void Insert(int X, List L, Position P)


{
Position Newnode;
Newnode = malloc (sizeof(Struct Node));
if (Newnode ! = NULL)
{
Newnode -> Element = X;
Newnode -> Next = P-> Next;
P -> Next = Newnode;
}
}
550
Header L 700 1000 800
10 20 30 40
550 P 700 1000 800
INSERT (25,P,L) 25 60
Newnode
ROUTINE TO DELETE AN ELEMENT FROM
THE LIST
void Delete(int X, List L)
{
position P,Temp;
P = Findprevious(X,L);
if (!IsLast(P,L))
{
Temp = P -> Next;
P -> Next = Temp -> Next;
Free (Temp);
}
} X
L 10 25 20
P Temp
BEFORE DELETION

L 10 20
61
AFTER DELETION
ROUTINE TO DELETE THE LIST

void DeleteList(List L)
{
position P, Temp;
P = L -> Next;
L -> Next = NULL;
while (P! = NULL)
{
Temp = P -> Next;
free (P);
P = Temp;
}
}

62
Header
L 10 20 L -> Next = NULL
L P

10 20 Temp = P -> Next


P Temp

20 free (P)
P = Temp
P

Temp,P = NULL

63
Advantage and Disadvantage Of SLL

Advantages of SLL:
1.The elements can be accessed using the next pointer
2.Occupies less memory than DLL as it has only one
next field.
Disadvantages of SLL:
1.Traversal in the backwards is not possible
2. Less efficient for insertion and deletion

64
Doubly Linked List

 Each node contains three fields namely


 Data Field
 Forward Link Field(FLINK)
 Backward Link Field(BLINK)
 FLINK points to successor node
 BLINK points to predecessor node

DATA
BLINK FLINK
ELEMENT

65
STRUCTURE DECLARATION

struct Node
{ DATA
BLINK FLINK
int Element; ELEMENT
struct Node *FLINK;
struct Node *BLINK;
};

Header
L
10 20 30 40

66
ROUTINE TO INSERT AN ELEMENT IN A
DOUBLY LINKED LIST
void Insert(int X, List L, Position P)
{
struct Node *Newnode;
Newnode = malloc(sizeof(struct Node));
if (Newnode ! = NULL)
{
Newnode -> Element = X;
Newnode -> Flink = P -> Flink;
P -> Flink -> Blink = Newnode;
P -> Flink = Newnode;
Newnode -> Blink = P;
}
}

Header
L
10 20 30
P
15 67
Newnode
ROUTINE TO DELETE AN ELEMENT

void Delete(int X, List L)


{
position P,Temp;
P=Find(X,L);
if( IsLast(P,L))
{
Temp = P;
P -> Blink ->Flink = NULL;
free (Temp);
}
else
{
Temp = P;
P -> Blink ->Flink = P -> Flink;
P -> Flink ->Blink = P -> Blink;
free (Temp);
}
}
Header
L
10 20 30
68
P
Advantage and Disadvantage Of Linked List

Advantage of DLL:
 Deletion operation is easier
 Finding the predecessor and successor of a node is
easier

Disadvantage of DLL:
 More memory space is required since it has two
pointers

69
Circular Linked List
Circular Linked List
In circular linked list the pointer of the last node points to the first
node. Circular linked list can be implemented as Singly linked list and Doubly
linked list with or without headers.

Singly Linked Circular List


A singly linked circular list is a linked list in which the last node of the
list points to the first node.

Header
L
10 20 30

70
Circular Linked List

Doubly Linked Circular List


A doubly linked circular list is a Doubly linked list in which the
forward link of the last node points to the first node and backward link of the
first node points to the last node of the list.

10 20 30

Advantages of Circular Linked List


• It allows traverse the list starting at any point.
• It allows quick access to the first and last records.
• Circularly doubly linked list allows to traverse the list in either direction.
71
Applications Of Linked List

 Polynomial ADT
 Radix Sort
 Multilist

72
THE STACK ADT

Stack Model:
A Stack is a linear data structure which follows Last In First Out
(LIFO) principle, in which both insertion and deletion occur at only one end of
the list called the Top.

Top C
B
A
Stack Model

Example :-
Pile of coins, a stack of trays in cafeteria.
73
Operations On Stack

 The fundamental operations performed on a stack are


1.Push
2.Pop

> Pop

Push

Operations on Stack

74
PUSH

Definition:
The process of inserting a new element to the top of the
stack .
For every push operation the top is incremented by 1.

Top=1 20
Top=0 10 10
Top=-1
Empty stack After inserting an After inserting an
element 10 element 20

Push Operations
75
POP

Definition:
The process of deleting an element from the top of stack is called pop
operation.
After every pop operation the top pointer is decremented by 1.

Top 8
Top
17 17
25 Top 25
25

Stack initially After the element 9 After the element


is deleted 17 is deleted

Pop Operations
76
EXCEPTIONAL CONDITIONS

Over Flow
 Attempt to insert an element when the stack is full
is said to be overflow.

Under Flow
 Attempt to delete an element , when the stack is
empty is said to be underflow.

77
Stack Size Explanation

Array Size =3

(Top=2) 7
6
5 5
(Top=0)
(Top=-1) Empty Stack Topsize=Arraysize-1

78
Implementation On Stack
1. Array Implementation
2. Linked List Implementation

79
Array Implementation of Stack
 Each Stack is associated with top value or pointer.
 Empty stack top value is -1.
 To Push an new X element onto the stack, Top pointer
is incremented and then set Stack[Top]=X.
 To Pop an element, the stack[Top] is returned and the
top pointer is decremented.
 Pop on empty stacks or push on full stack will exceed
the array bound.

Top 6

5
80
ROUTINE TO PUSH AN ELEMENT ONTO A STACK

void push(int X, Stack S)


{
if(Top = = Arraysize-1)
{
printf(“Full Stack and can’t insert an element”);
}
else Array Size=3
{
Top = Top + 1; 7 Top
S[Top] = X; Top 6 6
} 5 5
}

81
ROUTINE TO POP AN ELEMENT FROM THE STACK
void pop(Stack S, int X)
{
if (Top = = -1)
printf(“Empty Stack”);
else
{
X = S[Top];
Top = Top – 1;
}
}

Top 7
Top
6 6
Top 5 5
(size=-1) Empty Stack
82
ROUTINE TO RETURN TOP ELEMENT OF THE
STACK

int TopElement (Stack S)


{
if (! IsEmpty(s))
return S[Top];
else
printf(“Empty Stack”);
return 0;
}

Top 7

5
Top
83
Routine to check whether the stack is full
or not

int IsFull(Stack S)
{ else
if(Top==Arraysize-1) return false;
return true; }

Top 30 Arraysize=3
20 Top 0=10,Top 1=20,Top 2=30
10

84
Routine to check Whether the stack is
Empty or not

int IsEmpty(Stack S)
{
if(Top = = -1) else
return true; return false;
}

Top
(Size=-1)

85
LINKED LIST IMPLEMENTATION OF STACK

 Push operation is performed by inserting an element at the front of the list.


 Pop operation is performed by deleting at the front of the list.
 Top operation returns the element at the front of the list.

Linked List Implementation of Stack ADT


86
LINKED LIST IMPLEMENTATION OF STACK

Linked List Implementation of Stack ADT 87


DECLARATION FOR LINKED LIST IMPLEMENTATION
OF STACK

Struct Node;
typedef Struct Node *Stack;
int IsEmpty (Stack S);
Stack CreateStack (void);
void MakeEmpty (Stack S);
void push (int X, Stack S);
int Topelement (Stack S);
void pop (Stack S);

Struct Node
{
int Element;
Struct Node *Next;
};

88
ROUTINE TO CHECK WHETHER THE STACK IS EMPTY

int IsEmpty(Stack S)
{
if (top= = NULL)
return(1);
}

89
ROUTINE TO PUSH AN ELEMENT ONTO A STACK
void push (int X, Stack S)
{
Struct Node *newnode;
newnode = malloc (sizeof(Struct Node));
If (newnode = = NULL)
Error (“Out of Space”);
else
{
newnode -> Element = X;
newnode -> Next = top;
top= newnode;
}
}

90
ROUTINE TO POP FROM A STACK

Void pop(Stack S)
{
Struct Node *Tempcell;
If (IsEmpty(S))
Error(“Empty Stack”);
else
{
Tempcell = top;
top= top-> Next;
Free(Tempcell);
}
}

91
ROUTINE TO RETURN TOP ELEMENT IN A
STACK

int Top(Stack S)
{
If(! IsEmpty(s))
return top-> Element;
Error(“Empty Stack”);
return 0;
}

92
APPLICATION OF STACK

Some of the application of stack are:


 Evaluating arithmetic expression
 Balancing the symbols
 Towers of Hanoi
 Function calls
 8 Queen problem

93
Different Types of Notations To Represent
Arithmetic Expression

There are 3 different ways of representing the


algebraic expression.
They are
*INFIX NOTATION
*POSTFIX NOTATION
*PREFIX NOTATION

94
Types Of Notations

INFIX
In Infix notation, the arithmetic operator appears between the two operands to
which it is being applied.
For example:- 1. A+B 2.A/B+C

POSTFIX
The arithmetic operator appears directly after the two operands to which it
applies. Also called reverse polish notation. ((A/B)+C)
For example:- 1.AB+ 2.AB/C+

PREFIX
The arithmetic operator is placed before the two operands to which is applies.
Also called as polish notation. ((A/B)+C)
For example:- 1.+AB 2. +/ABC

95
1.Evaluating Arithmetic Expression

To evaluate an arithmetic expressions,


 First convert the given infix expression to postfix expression
 Evaluate the postfix expression using stack.

Infix to Postfix Conversion

Read the infix expression one character at a time until it encounters the delimiter.

Step1: If the character is an operand, place it on to the output.


Step2: If the character is an operator, push it onto the stack. If the stack operator has a
higher or equal priority than input operator then pop that operator from the stack
and place it onto the output.
Step3: If the character is a left parenthesis , push it onto the stack.
Step4: If the character is a right parenthesis, pop all the operators from the stack still it
encounters left parenthesis, discard both the parenthesis in the output.

96
2.BALANCING THE SYMBOLS

Read one character at a time until it encounters the delimiter ‘#’.

Step1: If the character is an opening symbol, push it onto the stack.


Step2: If the character is a closing symbol, and if the stack is empty report an error an
missing opening symbol.
Step3: If it is a closing symbol and if it has corresponding opening symbol in the stack,
POP it from the stack. Otherwise, report an error as mismatched symbols.
Step4: At the end of file, if the stack in not empty, report an error as Missing closing
symbol. Otherwise, report as Balanced symbols.

10
0
THE QUEUE ADT

Queue Model
A Queue is a linear data structure which follows First In First Out (FIFO)
principle, in which insertion is performed at rear end and deletion is performed at front
end.
Dequeue (Q) Enqueue (Q)
QUEUE
FRONT REAR

EXAMPLE : Waiting Line in Reservation Counter.

10
1
Operations on Queue

 The fundamental operation performed on Queue are,


1.Enqueue
2.Dequeue

Enqueue :
The process of inserting an element to the queue is
known as enqueue.

Dequeue :
The process of deleting an element from the queue
is known as dequeue.

10
2
Exception Conditions

Overflow :
 Attempts to insert an element, when the queue is full is said to
be overflow.

Underflow :
 Attempts to delete an element from the queue, when the queue
is empty is said to be underflow.

10
3
Implementation of Queue

Queue can be implemented using


 Arrays
 Linked List
Array Implementation:
In this implementation queue Q is associated with two
pointers namely rear pointer and front pointer.
To insert an element X onto the Queue Q, the rear pointer is
incremented by 1 and then set
Queue [Rear] = X
To delete an element, the Queue [Front] is returned and the
Front pointer is incremented by 1.

10
4
ROUTINE TO ENQUEUE

void enqueue (int X)


{
if (rear > = Arraysize-1) -1 0 1 2
printf(“Queue overflow”);
else
{ R F
Rear = Rear + 1; Empty Queue
Queue [Rear] = X;
}
}
0 1 2 0 1 2 0 1 2
10 10 27 10 27 30
F,R F R F R

10
5
ROUTINE TO DEQUEUE
void dequeue()
{ 0 1 2
if (Front < 0)
printf(“Queue Underflow”); 10 27
else
{ F R
X = Queue[Front];
if (Front == Rear) 27
{
Front = 0; F,R
Rear = -1;
}
else
Front = Front + 1;
}
}

10
6
Illustration for array implementation of
queue

-1 0 1 2 3 4 0 1 2 3 4

R F EMPTY QUEUE R,F ENQUEUE

10 15 15
0 1 2 3 4 0 1 2 3 4

ENQUEUE (15) DEQUEUE (15)


F R F,R

In Dequeue operation, if Front = Rear, then reset


both pointers to their initial values.
-1 0 1 2 3 4 (i.e F = 0 , R = -1)

R F DEQUEUE (Q) 10
7
Types of Queue

1. DEQUE
2. Priority Queue
3. Circular Queue
Double Ended Queue (DEQUE)

Definition:
In DEQUE, both insertion and deletion are performed in
both ends.
Insertion Insertion
Deletion 10 20 30 40 50 60 70 80 Deletion

DEQUE has two types


 Input restricted DEQUE
 Output restricted DEQUE
Types of DEQUE

Input restricted DEQUE


 Insertion at only one end
 Deletion at both ends
Insertion
Deletion Deletion

Output restricted DEQUE


 Deletion at only one end
 Insertion at both ends
Deletion
Insertion Insertion
Priority Queue

 A Priority queue is an abstract data type which is like a


regular queue , but where additionally each element has a
"priority" associated with it.
 An element with high priority is served before an element with
low priority.
 If two elements have the same priority, they are served
according to the order in which they were in queue.
Applications Of Priority Queue:

Applications:
– CPU scheduling
– Graph algorithms like Dijkstra’s shortest path, Prim’s
and minimum spanning tree, etc,.
CIRCULAR QUEUE

• A Circular Queue is an extended version of a normal queue where the last


element of the queue is connected to the first element of the queue forming a
circle.
• The operations are performed based on FIFO (First In First Out) principle. It is
also called ‘Ring Buffer’.

Advantages
• It overcomes the problem of unutilized space in linear queue, when it is
implemented as array.
Insertion in Circular Queue

FRONT
Q[5] Q[0]
Q[5] Q[0]
- -
10
Q[4] - - Q[1]
Q[4] 20 Q[1]

- -
REAR FRONT
30
Q[3] Q[2] Q[5] Q[0] Q[3] Q[2]
60 10
REAR
Q[4] 50 20 Q[1]

40 30

Q[3] Q[2] 11
4
ASYMPTOTIC NOTATIONS

ASYMPTOTIC NOTATION: The mathematical way of representing


the Time complexity.
It is used to express the execution time of an algorithm and to
compare the efficiency of various algorithm.

Definition : It is the way to describe the behavior of functions in


the limit or without bounds.
There are 3 asymptotic notations that are used to represent time
complexity of algorithm.

1.Big oh (O)notation
2.Big omega (Ω) notation
3.Theta(Θ) notation
Big oh (O)notation
• Asymptotic “less than”(slower rate).
• This notation mainly represent upper bound of algorithm run time.
• Big oh (O)notation is useful to calculate maximum amount of time of
execution.
• By using Big-oh notation we have to calculate worst case time complexity.

Formula : f(n)<=c g(n) n>=n0 , c>0 ,n0 >=1


Definition: Let f(n) ,g(n) be two positive functions
now the f(n)=O(g(n))
if there exist two positive constant c, n0 such that
f(n)<= c.g(n) for all value of n>=n0 ,
1.Big O-notation
 For a given function 𝑔(𝑛) , we denote by 𝑂(𝑔(𝑛))
the set
of functions

𝑓(𝑛) : there exist positive constants 𝑐 and 𝑛0 s.t.


𝑂(𝑔(𝑛)) =
0 ≤ 𝑓(𝑛) ≤ 𝑐𝑔(𝑛)for all 𝑛 ≥ 𝑛0
Examples
2.Ω-Omega notation

• Asymptotic “greater than”(faster rate).


• It represent Lower bound of algorithm run time.
• By using Big Omega notation we can calculate minimum amount of
time.
• We can say that it is best case time complexity.

Formula : f(n)>=c g(n) n>=n0 , c>0 ,n0 >=1


OR
c g(n)<= f(n)

where c, n0 are positive constants


Lower bound
Best case
Ω-Omega notation
DEFINITION

 For a given function 𝑔(𝑛), we denote by Ω(𝑔(𝑛)) the set of functions


𝑓(𝑛) : there exist positive constants 𝑐and𝑛0 s.t.
Ω(𝑔(𝑛)) =
0 ≤ 𝑐𝑔(𝑛) ≤ 𝑓(𝑛)for all 𝑛 ≥ 𝑛0

• 𝑓(𝑛) = Ω(𝑔(𝑛)) means that there exists some constant c s.t.


𝑓(𝑛) is always ≥ 𝑐𝑔(𝑛) for large enough n.
Examples
3. Ꝋ -Theta notation

• Asymptotic “Equality”(same rate).


• It represent average bound of algorithm running time
• By using theta notation we can calculate average
amount of time.
• So it called average case time complexity of algorithm.

Formula : c1 g(n)<=f(n)<=c2 g(n)


where c1, c2, n- constant

Average bound
Ꝋ-Theta notation

 For a given function 𝑔(𝑛) , we denote by Θ(𝑔(𝑛))


the set
of functions
𝑓(𝑛) : there exist positive constants 𝑐1 , 𝑐2 , and𝑛0 s.t.
Θ(𝑔(𝑛)) =
0 ≤ c1 𝑔(𝑛) ≤ 𝑓(𝑛) ≤ 𝑐2 𝑔(𝑛)for all 𝑛 ≥ 𝑛0

 A function 𝑓(𝑛) belongs to the set Θ(𝑔(𝑛)) if there exist


positive constants 𝑐1 and 𝑐2 such that it can be “sand-
wiched” between 𝑐1 𝑔(𝑛) and 𝑐2 𝑔(𝑛) or sufficienly large n.
 𝑓(𝑛) = Θ(𝑔(𝑛)) means that there exists some constant c1
and c2 s.t. 𝑐1 𝑔(𝑛) ≤ 𝑓(𝑛) ≤ 𝑐2 𝑔(𝑛) for large enough n.
Examples
Application Of Queue

 Batch Processing in operating system


 To implement priority queue
 Priority queues can be used to sort the elements
using heap sort
 Simulation
 Mathematics user queuing theory
 Computer networks where the server takes the job
of the client as per the queue strategy.
 Responding customer calls in Call Center
 Printer
Data Structure

DECLARATION FOR LINKED LIST IMPLEMENTATION


OF POLYNOMIAL ADT
Struct poly
{
int coeff;
int power;
Struct poly *Next;
} *list1, *list2, *list3;
CREATION OF THE POLYNOMIAL

poly create(poly *head1,poly *newnode1)


{
poly *ptr;
If (head1 == NULL)
{
head1 = newnode1;
return(head1);
}
else
{
ptr = head1;
while(ptr -> next! = NULL)
ptr = ptr -> next;
ptr -> next = newnode1;
}
return (head1);
}
12
9
ADDITION OF TWO POLYNOMIALS

void add()
{
poly *ptr1, *ptr2, *newnode;
ptr1 = list1;
ptr2 = list2;
while (ptr1! = NULL && ptr2! = NULL)
{
newnode = malloc(sizeof(Struct poly));
if (ptr1 -> power == ptr2 -> power)
{
newnode -> coeff = ptr1 -> coeff + ptr2 ->coeff;
newnode -> power = ptr1 -> power;
newnode -> next = NULL;
list3 = create(list3,newnode);
ptr1 = ptr1 -> next;
ptr2 = ptr2 -> next;
}
else 13
{ 0
if (ptr1 -> power > ptr2 -> power)
{
newnode -> coeff = ptr1 - > coeff;
newnode -> power = ptr1-> power;
newnode -> next = NULL;
list3 = create(list3,newnode);
ptr1 = ptr1 -> next;
}
else
{
newnode -> coeff = ptr2 -> coeff;
newnode -> power = ptr2 -> power;
newnode -> next = NULL;
list3 = create(list3,newnode);
ptr2 = ptr2 -> next;
}
}
} 13
1
MULTILIST

 More complicated application of linked list is multilist.


 Multilist saves memory space
 Takes more time to implement.

E1 E2 E3

P1

P2

13
2
Application of Linked List

Input:
1st number = 5x + 4x + 2x
2 1 0

2nd number = -5x - 5x 1 0

Output: 5x -1x -3x


2 1 0
Application of Linked List
Data Structure

DECLARATION FOR LINKED LIST IMPLEMENTATION


OF POLYNOMIAL ADT
Struct poly
{
int coeff;
int power;
Struct poly *Next;
} *list1, *list2, *list3;

You might also like