0% found this document useful (0 votes)
24 views153 pages

Data Structure

......

Uploaded by

Tribute King
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)
24 views153 pages

Data Structure

......

Uploaded by

Tribute King
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/ 153

About Instructor

Mr. Wahab Ahmad (Lecturer)


Subject: Data Structures and Algorithms (2+ 1)

Department of Software Engineering Technology


Punjab Tianjin University of Technology,
Lahore
Arrays and Abstract Data
Types
Data Structure
What is a data structure ?
• A data structure is a specialized format for organizing and storing data.
• It is a way to store data on a computer which we define logically.
• A data structure helps the user to store data in such a way that it can be used and processed
efficiently.
Types of Data Structures
• Linear data structures
• Non-Linear Data structures
Linear Data Structures
• A type of data structure in which the data elements are stored in a linear sequence is known as
linear data structures. Array, stack, queue and linked list are examples of linear data structures.
Non-Linear Data Structures
• A type of data structure in which the data elements are stored in a non-linear sequence is
known as non-linear data structures. Trees and graphs are examples of non-linear data
structures.
Array Data Structure
An array is a group of related data items with same name and type.
These group of related items are stored in adjacent / consective memory locations
Each data items in an array is known as the element of the array
The total number of elements in an array is called the length of array
Arrays are used to store a large amount of similar kind of data
Each element in the array is accessed by with reference to its position of location in the array
The position of an array element is called index
Each element in the array has unique index
The index of first element is 0 and the last element is length-1
Advantages of array
Some advantages of arrays are as follows:
❖ Arrays can store a large number of values with single name
❖ Arrays are used to process many values easily and quickly
❖ The values stored in an array can be sorted easily
❖ A search process can be applied on array easily
Declaring One-Dimensional Array
❖ The process of specifying array name, length and data type is called array declaration
Syntax
❖ Data_Type identifier [length];

Data_TypeIt indicates the data type of the values stored in


Identifier the array It indicates the name of the array
Length It indicates total number of elements in the
Examplearray
int marks[5];
indexe 0 1 2 3 4
s
Array Mark
name s
Array Initialization
The process of assigning values to array elements at the time of array declaration is called array
initialization
The values are separated with commas and enclosed within braces
A syntax error occurs if the values in braces are more than the length of the array
Syntax
❖ Data_Type It indicates
Data_Type identifier [Length] the data
= {List type of the values stored in the array It
of values};
Identifier indicates the name of the array

Length It indicates total number of elements in the array It


List of values indicates the values to initialize the array
Example int marks[5] = {70,54,60,76,66}
indexe 0 1 2 3 4
Array s Marks 70 54 60 76 66
name
Accessing Array Elements
Accessing Individual Elements of Array
❖ Each individual element of an array is accessed by specifying the following:
• Name of array
• Index of element
Syntax
❖ Array_Name[index]

Array_Name It indicates the name of array


Index It indicates the index of elements to be accessed

Example
int marks[2];
marks[0]= 20;
marks[1]= 50;
Accessing array elements using loops
❖ int marks[5];
for(int i=0; i<5;
i++) marks[i]=i
Input and Output Values of an Array
Write a program that inputs five integers from the user and stores them in an array. It then displays all valu
the array using loops
Output
#include<iostream>
Enter an integer: 96
using namespace std; Enter an integer: 72
int main(){ Enter an integer: 41
int array[5], i; Enter an integer: 39
for(i=0; i<5; i++) Enter an integer: 68
{ The values in array
cout<<“Enter an integer:”; are: 96
cin>> arr[i]; 72
} 41
cout<<“The values in array are: \n; 39
for(i=0; i<5; i++) 68
cout<<arr[i]<<endl;
return;
}
Operations on Linear Arrays
Several Operations can be performed on linear arrays.
The most important of these operations include
• Traversing
• Inserting
• Deleting
• Searching & Sorting
Traversing Operation
In traversing operation, each element of an array is access exactly once for processing
For example, to compute the sum of values of each element of an array, all elements of array are
accessed exactly once and their values are added.
Inserting Operation
In inserting operation, new items are added into an array. A new item can be added:
• At the end of array without disturbing other elements of the array if there is an empty element.
• At some specified location within the array
Inserting Value at Specified Location in an Array

To insert a new value


• Values of all the existing elements are moved one step forward or backward to make space for the
new value
Algorithm – Inserting value at a specified location
1. Start
2. Input value in newItem
3. Input position in pos
4. Input array length in n
5. i = n
6. Repeat step 7 to 8 while i > pos
7. arr[i] = arr[i-1]
8. i = i -1
9. arr[pos] = newItem
10. Exit
Deleting Operation
In deleting operation, the element(s) of an array are removed. Like insertion, deletion can be
performed at the end or at any position in the array

Deleting items at the End


To remove the last element from the array
• last element is accessed and replace the null/0 value by its value
• By decreasing the size of array by one element of array
Index

0 1 2 3 4
12 15 3 100 92

item
Deleting Operation
Deleting item from a Specified Location
To remove the item from the array at specified location
• By removing the item, Items from the location up to end of array are moved one location towards
the beginning of the array.
• The size of array also decrease

Index

0 1 2 3 4
12 15 3 100 92

item
Algorithm – Deleting item from array

1. Start
2. Input location in K
3. Input array length in N
4. IF K > =N || K < 0 then
1. Print “Invalid Location”
2. Return
3. END IF
5. Repeat For C = K To N-1
1. Arr[C] = Arr [ C+1]
2. C = C+1
6. Arr[N-1] = 0
7. Exit
Searching and Sorting Arrays
The process of finding a specific data item and its location is called searching
These are different searching techniques
• Linear Search
• Binary Search

The process of rearranging items of an array in a specific order is called sorting


These are different sorting algorithm
• Bubble Sort
• Selection Sort
• Insertion Sort
Two-Dimensional Arrays
Two-dimensional array can be considered as a table that consists of rows and columns
Each element in 2-D array is referred with the help of two indexes. One index is used to
indicate the
row and the second index indicates the column of the element.

Syntax
Data_Type identifier[Rows][Cols]
Data_Type It indicates the data types of the values to be stored in the array It
Identifier indicates the name of the array
Rows It indicates the number of rows in the 2-D array It
Cols indicates the number of columns in the array
Example
❖ The following statement declares a 2-D array with four rows and three
columns:
• Int Arr[4][3];
Two-Dimensional Arrays
The statement int Arr[4][3];
❖ The statement declares a two-dimensional array. The first index indicates array contains four
rows.
❖ The index of first row is 0 and the index of last row is 3.
❖ The second index indicates that each row in the array contains three columns.
❖ The index of first column is 0 and the index of last column is 2.
❖ The total number of elements can be determined by multiplying rows and columns.
❖ The above array contains twelve elements
0 1 2
0 0,0 0,1 0,2
Column indexes
1 1,0 1,1 1,2
Row indexes 2 2,0 2,1 2,2

3,0 3,1 3,2


3

A 2-D array and its


Accessing Individual Elements of 2-D Array
The array name and indexes of rows and column are used to store access an individual elements
of 2-D
array
The following statement will store 100 in the second column of first row in the array:
❖ Arr[0][1] = 100;
❖ The index for row or column of 2-D array can be given using variables. The following
example will work similar to the above:
R=0;
C=1; Arr[R][C]=100
Entering Data in 2-D Arrays
❖ You can enter data in any element of the array by using the name of array and index of
the element. The following statements enter data in the first row of a 2-D array.
Arr[0][0] =10 10 stored in first column of first
Arr[0][1] =20 row 20 stored in 2nd column of
Arr[0][2] =30 first row 30 stored in third column
of first row
Input and Output Values of an 2-D Arrays
Write a program that inputs five integers from the user and stores them in an array. It then displays all
values in the array using loops
#include<iostream>
Output
using namespace std;
void main(){ Enter an integer:
int array[2][4], i,j; 10 Enter an The values in array
for(i=0; i<2; i++) integer: 20 Enter are:
10 20 30 40
for(j=0; j<4; j++) an integer: 30
50 60 70 80
{ Enter an integer:
cout<<“Enter an integer:”; 40 Enter an
cin>> arr[i][j]; integer: 50 Enter
} an integer: 60
cout<<“The values in array are: \n; Enter an integer:
for(i=0; i<2; i++){ 70 Enter an
for(j=0; j<4; j++) integer: 80
cout<<arr[i][j]<<“\t”;
cout<<endl;
getch();
}
Initializing 2-D Arrays
Syntax of Initializing 2-D Arrays
❖ int Arr[3][4]=
{ { 12,5,22,84},
{95,3,41,59},
{77,6,53,62}};
The above example declares an array of integers with three rows and four columns
The first inner braces contain the values for row 0.
The 2nd inner braces contain the values for row 1.
The 3rd inner braces contain the values for row 2.

01 2 3
0
12 5 22 84
1 95 3 41 59
2 77 6 53 62
Searching in Arrays
Searching is the process of finding the required data in the array. Searching becomes more
important when the length of the array is very large.

Sequential Search
Sequential search is also called linear search or serial search. It is a simple way to search an array
for the desired value. It follows the following steps to search a value in array:

• Visit the first element and compare its value with the required value.
• If the value of array matches with the desired value, the search is complete.
• If the value of array does not match, move to next element and repeat same process.

Loops are frequently used to visit elements of array for searching a value. You can start the counter
variable of loop from 0 and move it to last index of array. For example if the array to be searched
has 10 elements, the loop will start the counter variable from 0 and move to 9.
Algorithm: Linear Sequential Search
1. SET LOC = -1
2. INPUT ITEM [Enter value that is to be searched]
3. REPEAT STEP-4 FOR I = 0 TO N
4. IF ITEM = ABC[I] THEN
LOC = I
EXIT
5. END IF[End of step-3 loop]
6. IF LOC = -1 THEN
PRINT "Item not Found"
ELSE
PRINT “Item Found at location”
END IF
7.
Binary Search
Binary search is a quicker method of searching for value in the array.
Binary search is very quick but it can only search an sorted array.

It follows the following steps:


1. It locates the middle element of array and compares with the search
number.
2. If they are equal, search is successful and the index of middle element is
returned.
3. If they are not equal, it reduces the search to half of the array.
4. If the search number is less than the middle element, it searches the first
half of array. Otherwise it searches the second half of the array. The
process continues until the required number is found or loop completes
without successful search.
Binary Search Example

Search Element 45

Sorted Array

1 3 16 20 32 50

Index: 0 1 2 3 4 5
Binary Search Example
Start 0
end 6
mid 3
First Iteration:

1 3 16 20 32 45 50

Index: 0 1 2 3 4 5 6
Binary Search Example
Start 4
end 6
mid 5
Second Iteration:

1 3 16 20 32 45 50

Index: 0 1 2 3 4 5 6
Binary Search Example
Start 5
end 6
mid 5
Third Iteration:

1 3 16 20 32 45 50

Index: 0 1 2 3 4 5 6

Element 45 Found at Index 5


Algorithm: Binary Sequential Search
1. SET LOC = -1
2. INPUT ITEM [Enter value to be searched]
3. START = Array First Index
4. END = Array Last Index
5. WHILE(START <= END)
1. MID = (START +END) / 2
2. IF ITEM = ABC[MID] THEN
LOC = MID
BREAK
END IF
3. ELSE IF ITEM < ABC[MID] THEN
END = MID -1
ELSE
START = MID +1
END IF
END WHILE
6. IF LOC = -1 THEN
PRINT "Data not found“
ELSE
PRINT "Data found at location“
END IF
Abstract data type
What is a data type?
❖ It defines a set of values and a set of operations on those values
❖ For example : In int data type only integer values are taken and operations like addition,
subtraction, division and multiplication etc. are allowed on these values
What are user defined data types?
❖ The values and operations of user defined data types are not specified in the language itself but is specified
by the user
❖ Example: Classes
❖ In structures, we define our type called user defined data type by combining different data types
❖ class Student{
int id;
char name[8];
};
❖ Student is a user defined data type which has two data types int and char.
Abstract data types are like user data types which defines operations on values using functions
without specifying what is there inside the function and how the operations are performed
❖ Example: Stack ADT
❖ A stack contains of elements of same data type organized in a sequential order.
❖ Operations
❖ Push() Insert an element into the stack
❖ Pop() Delete an element from the stack
Abstract Data Types
These are some operations which we are specifying on stack. These are also functions but we are not
defining how they can be implemented. We are just specifying them that is called abstract data type.
❖ We know what kind elements are allowed and also operations on it, but we do not what is inside.
❖ Push is also function name which performs push operation
❖ Pop is also function name which performs pop operation

class StackADT{
private:
int array[10] = {1, 2, 4 , 5, 10, 11, 13, 14, 17, 20};

public:
void push(int item);
void pop();
};
Abstract Data Types
An abstract data type is a set of data together with a set of operations.
Objects such as lists and sets along with their operations can be viewed as ADTs.
The C++ class allows for the implementation of ADTs, with appropriate hiding of
implementation details
Benefit of Abstract data type
❖ If someone wants to use stack in the program, then he can simply use the push and pop
• operations without knowing its implementation
❖ If for some reasons implementation details need to be changed.
❖ For example the implementation of stack is changed from array to linked list it does
not affect the user, he can just use abstract data type by calling its functions
❖ So abstract data type provides abstraction
STACKS
STACKS
• A stack is a special kind of linear list in which only two operations, insertion and deletion can be
performed.
• These operations may occur only at its top end.
• Items in it are stored and retrieved in Last In First Out (LIFO) Push Pop

Example of Stack is dish rack


Dish rack holds dishes in such a manner that only the top dish is visible

items
item3

item2
STACK

item1
Representation of Stacks
A stack is usually represented by a linear array in the computer memory

Top
Bottom
66 75 77 69
0 1 2 3 4 5 6 7

The most accessible item in the stack is called the Top of the stack.
The least Accessible Item is called Bottom of the stack
Stack Operations
The only two operations that can be performed on a stack are insertions and deletion

Pushing
• The process of inserting or adding new items into stack is called Pushing.
• Before pushing an item into a stack, it is tested whether or not there is any room in the stack to store
item.
• If there is no room in the stack, then the stack condition is known as a overflow

Popping
• The process of removing or deleting item from a stack is called Popping.
• Before removing an item from a stack it is tested whether or not at least one element exists in the
stack.
• If no element exists in a stack, i.e. the stack is empty, the condition is known as underflow.
Push Procedure – Push(Item)
1. START
2. IF TOP =N-1 THEN
1. PRINT “STACK OVERFLOW”
2. RETURN
3. ENDIF
4. TOP = TOP +1
5. S[TOP] = ITEM
6. END
Pop Procedure – Pop()
1. START
2. IF TOP =-1 THEN
1. PRINT “STACK UNDERFLOW”
2. RETURN
3. ENDIF
4. TOP = TOP -1
5. ITEM = S[TOP]
6. RETURN ITEM
7. END
Evaluation of Expressions
● An arithmetic expression is made up of operands, arithmetic operators and parentheses.
● The operands may be numeric variables or numeric constants

Some Examples of arithmetic expressions are:


A+B, X*Y, A*(B-C) / 2, (A+B)^2

● The arithmetic operators +, -, * and / are the same that are used in ordinary algebra
● The operator ^ is used as to compute the exponential.

Note: The expression is always evaluated from left to right.

The order in which the express is evaluated as


● if the expression has parenthesis, then they are evaluated first.
● Exponential (^) is given highest priority.
● Multiplication (*) and division (/) have the next highest priority.
● Addition (+) and subtraction (-) have the lowest priority.
Polish Notation
Infix Notation
In most arithmetic expressions, the arithmetic operator is placed between two operands, e.g. x + y,
x / y. This type of notation is called infix notation.

Polish/ Prefix Notation


In polish notation, the arithmetic operator is placed before its two operands. The operators are used
before the operands in polish notation, it is also called prefix notation

Infix Notation Polish Notation

X+Y +XY

X/Y /XY

(X + Y) * Z *+XYZ
Reverse Polish Notation or Postfix Notation
In this notation the arithmetic operator is placed after the operands. This notation is also known as suffix
notation.
The following shows expressions in infix notation and equivalent prefix and postfix notations.

Infix Prefix Postfix


(Polish Notation) (Inverse Polish Notation)

A+B +AB AB+

A*B *AB AB*

A/B /AB AB/

A-B -AB AB-

Note: Parentheses are not used in Prefix and Postfix


Evaluation of Expression in Computer
● The computer evaluates an expression given in infix notation by converting it into postfix notation.
● The stack is used to perform this operation.

The following steps are taken to evaluate a postfix expression:

1. The express is scanned from left to right until the end of the expression.
2. When an operand is encountered, it is pushed into stack.
3. When an operator is encountered, then:
a. The top two operands of stack are removed
b. The arithmetic operation is performed
c. The computed result is pushed back to the stack
4. When end of the expression is reached, the top value from the stack is picked. It is the computed
value of the expression.
Evaluation of Expression in Computer
Evaluate expression AB/C-DE*+ when A=12, B=6, C=3, D=4 & E=5

Let's begin to scan from left to right

Iteration 1: Push the A into stack

A=12

Iteration 2: Push the B into stack


B=6

A=12
Evaluation of Expression in Computer
Evaluate expression AB/C-DE*+ when A=12, B=6, C=3, D=4 & E=5

Let's begin to scan from left to right

Iteration 3: / operator is found. Pop top two


operands, perform division and push result into
stack. 2

Iteration 4: Push the C into stack


C=3

2
Evaluation of Expression in Computer
Evaluate expression AB/C-DE*+ when A=12, B=6, C=3, D=4 & E=5

Let's begin to scan from left to right

Iteration 5: - operator is found. Pop top two


operands, perform subtraction and push result
into stack. -1

Iteration 6: Push the D into stack


D=4

-1
Evaluation of Expression in Computer
Evaluate expression AB/C-DE*+ when A=12, B=6, C=3, D=4 & E=5

Let's begin to scan from left to right

E=5
Iteration 7 : Push the E into stack
D=4

-1

Iteration 8: * operator is found. Pop top two


operands, performt multiplication and push 20

result into stack. -1


Evaluation of Expression in Computer
Evaluate expression AB/C-DE*+ when A=12, B=6, C=3, D=4 & E=5

Let's begin to scan from left to right

Iteration 9: + operator is found. Pop top two


operands, perform addition and push result into
stack. 19
Infix to Postfix Conversion
The stack is used to convert an infix expression to postfix. The stack is used to store operators and then
pass to the postfix expression according to their precedence.

The infix expression is converted into postfix expression according to the following rules:
1. The infix expression is scanned from left to right until end of the expression. The operand are passed
directly to the output. Whereas, the operator are first passed to the stacks
2. Whereas an operand is encountered, it is added to the output, i.e. to the postfix expression.
3. Each time an operator is read, the stack is repeatedly popped and passed to the output, until an
operator is reached that has a lower precedence than the most recently read operator. The most
recently read operator is then pushed onto the stack.
4. When end of expression is reached, then all operators from stack are popped and added to the
output.
Infix to Postfix Conversion
5. Parentheses can be used in the infix expression but these are not used in the postfix expression.
During conversion process, parentheses are treated as operators that have higher precedence than
any other operator. The left parenthesis is pushed into the stack when encountered.
6. The right parenthesis is never pushed to the stack. The left parenthesis is popped only when right
parenthesis is encountered. The parentheses are not passed to the output postfix expressions; they
are discarded.
7. When end of expression is reached, then all operators from stack are popped and added to the
output.
Infix to Postfix Conversion
Convert the following infix expression in postfix expressions:

● (A + B) * C
● A + ( B * C)
● A+ B * C + (D * E + F) * G
Infix to Postfix Conversion
(A + B) * C
(A+ B) * C )

Steps Symbol Scanned Stack Output

1 ( (

2 ( ((

3 A (( A

4 + ((+ A

5 B ((+ AB

6 ) ( AB+

7 * (* AB+

8 C (* AB+C

9 ) AB+C*
Infix to Postfix Conversion
A + (B * C)
A + (B * C))

Steps Symbol Scanned Stack Output

1 ( (

2 A ( A

3 + (+ A

4 ( (+( A

5 B (+( AB

6 * (+(* AB

7 C (+(* ABC

8 ) (+ ABC*

9 ) ABC*+
Infix to Postfix Conversion
A + B* C + (D * E + F) * G
A + B* C + (D * E + F) * G)

Steps Symbol Scanned Stack Output

1 ( (

2 A ( A

3 + (+ A

4 B (+ AB

5 * (+* AB

6 C (+* ABC

7 + (+ ABC*+

8 ( (+( ABC*+

9 D (+( ABC*+D
Infix to Postfix Conversion
A + B* C + (D * E + F) * G
A + B* C + (D * E + F) * G)

Steps Symbol Scanned Stack Output

10 * (+(* ABC*+D

11 E (+(* ABC*+DE

12 + (+(+ ABC*+DE*

13 F (+(+ ABC*+DE*F

14 ) (+ ABC*+DE*F+

15 * (+* ABC*+DE*F+

16 G (+* ABC*+DE*F+G

17 ) ABC*+DE*F+G*+
Infix to Prefix Conversion
The stack is used to convert an infix expression to postfix. The stack is used to store operators and then
pass to the prefix expression according to their precedence.

The infix expression is converted into prefix expression according to the following rules:
1. Reverse the infix expression
2. Convert the reversed infix expression to “nearly” postfix expression.
3. While converting to postfix expression, instead of using pop operation to pop operators with greater
than or equal precedence, here we will only pop the operators from stack that have greater
precedence.
4. Reverse the postfix expression.
Infix to Prefix Conversion
Convert the following infix expression in postfix expressions:

● A*B+C/D
● (A – B / C) * ( A/ K - L)
Infix to Prefix Conversion
A*B+C/D
D/C+B*A Steps Symbol Scanned Stack Output
D / C + B * A) 1 (

2 D ( D

3 / (/ D

4 C (/ DC

5 + (+ DC/

6 B (+ DC/B

7 * (+* DC/B

8 A (+* DC/BA

9 ) DC/BA*+

+*AB/CD
Infix to Prefix Conversion
(A-B/C) * (A/K-L)
(L-K/A)*(C/B-A)
(L-K/A)*(C/B-A))

Steps Symbol Scanned Stack Output

1 (

2 ( ((

3 L (( L

4 - ((- L

5 K ((- LK

6 / ((-/ LK

7 A ((-/ LKA

8 ) ( LKA/-

9 * (* LKA/-
Infix to Prefix Conversion
(A-B/C) * (A/K-L)
(L-K/A)*(C/B-A)
(L-K/A)*(C/B-A))

Steps Symbol Scanned Stack Output

10 ( (*( LKA/-

11 C (*( LKA/-C

12 / (*(/ LKA/-C

13 B (*(/ LKA/-CB

14 - (*(- LKA/-CB/

15 A (*(- LKA/-CB/A

16 ) (* LKA/-CB/A-

17 ) LKA/-CB/A-*

*-A/BC-/AKL
Recursion
A procedure that calls itself, either directly or indirectly, is called recursive procedure and the process is
called recursion.

The process in which a procedure calls itself is called direct recursion.


The process in which a procedure A calls another procedure B, which is in turn calls the procedure A is
called indirect recursion.

The number of times a function is called recursively is called depth of recursion.


Conditions for Recursive Procedures
There are two important conditions that must be satisfied by any recursive procedure. These conditions
are required to prevent the recursive procedure from running indefinitely.
These are conditions are that:

• There must be a criteria for existing from the recursive procedure. The condition at which the control
exits from procedure is known as the Base Criteria
• Each time the procedure is called directly or indirectly, the condition must get closer to the Base
Criteria
Implementation of Recursive Procedure by Stacks
A recursive procedure can be executed several times. It receives values from the calling procedure and
transmits results back to it.

The recursive function terminates execution when the base criteria is reached. It then returns parameters
and variables to the calling procedures. It return these values such that the values from the last execution
are returned first.

The last-in and first-out characteristics of a recursive procedure shows that a stack is the most suitable
data structure to implement it.
Recursive Procedure Example
FACTORIAL (N)
1. IF N = 0 THEN
RETURN 1
ELSE IF
RETURN N * FACTORIAL(N-1)
QUEUE
Queue
A queue is a special type of linear structure. It holds a series of items for processing on a first in first out
basis.

Element can only be inserted to the Rear of a queue, and deleted from Front of queue.

Example

• An example of a queue in real world is a queue of people waiting to buy tickets. The person who
came first in the queue will be given the ticket first. The person who joined the queue at last time is
entertained last.
• The position of the first person is not changed if a new person joins the queue because he is added at
the end.
• The positions of all persons in the queue are changed when the first person buys the ticket and leaves
the queue. In this situation, each person in the queue moves one step forward.
Queue Data Structure
Representation of Queue
A queue can be represented in computer in two ways:

Queue using Arrays


A queue can be represented by using arrays. The length of an array represents the maximum number of
data elements that can be inserted in the queue.
The user cannot insert unlimited number of items in it. The representation of queue with array is simple
and easier to implement.

Queue using Linked List


A queue can be represented by allocating memory dynamically using linked list. The length of the queue
is not specified in program code.
The dynamic representation of queue with pointers is more complex to implement but it
provides flexibility.
Queue

Insertion Deletion Front = -1


Rear = -1

0 1 2 3 4 5 6 7

Rear Front
Queue - Insertion
Insertion Deletion Front = 0
Rear = 0

45
0 1 2 3 4 5 6 7

Rear Front
Insertion Deletion Front = 0
Rear = 1

45 21
0 1 2 3 4 5 6 7

Rear Front
Queue - Insertion
Insertion Deletion Front = 0
Rear = 2

45 21 77
0 1 2 3 4 5 6 7

Rear Front
Insertion Deletion Front = 0
Rear = 3

45 21 77 23
0 1 2 3 4 5 6 7

Rear Front
Queue - Deletion
Insertion Deletion Front = 1
Rear = 3

21 77 23
0 1 2 3 4 5 6 7

Rear Front
Insertion Deletion Front = 2
Rear = 3

77 23
0 1 2 3 4 5 6 7

Rear Front
Algorithm - Insertion
1. START
2. IF R == N THEN
PRINT “Overflow”
RETURN
ELSE
R=R+1
Q[R] = Item
ENDIF
3. IF F = -1 THEN
F=0
END IF
4. EXIT
Algorithm - Deletion
1. START
2. IF F=-1 THEN
PRINT “Underflow”
RETURN
ENDIF
3. Del = Q[F]
4. IF F = R THEN
F = R = -1
ELSE
F=F+1
END IF
5. EXIT
Circular Queue
Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In
First Out) principle and the last position is connected back to the first position to make a circle.

0
12 1
42

5 92
43 2

22
16
4
3
Algorithm - Insertion
1. START
2. IF (R+1)%N = F THEN
PRINT “Overflow”
RETURN
ELSE
R = (R + 1)%N
Q[R] = Item
ENDIF
3. IF F = -1 THEN
F=0
END IF
4. EXIT
Algorithm - Deletion
1. START
2. IF F=-1 THEN
PRINT “Underflow”
RETURN
ENDIF
3. Del = Q[F]
4. IF F = R THEN
F = R = -1
ELSE
F = (F + 1)%N
END IF
5. EXIT
Priority Queue
• A priority queue is a more specialized data structure than a stack or a queue.
• Like an ordinary queue, a priority queue has a front and a rear, and items are removed from the front.
• However, in a priority queue, items are ordered by key value so that the item with the lowest key (or
in some implementations the highest key) is always at the front. Items are inserted in the proper
position to maintain the order.

Applications of Priority Queue

• Like ordinary queues, priority queues are used in various ways in certain computer systems. In a
preemptive multitasking operating system, for example, programs may be placed in a priority queue
so the highest-priority program is the next one to receive a time-slice that allows it to execute.
Priority Queue

Q1
0 1 2 3 4

Q2
0 1 2 3 4

Q3
0 1 2 3 4

Q4

0 1 2 3 4
Deques
• The term deque stands for double-ended queue. Items can be added or deleted at both ends of the
deque, it is called double-ended queue

The deque is represented as shown in the following figure:

Deletion Deletion
Insertion Insertion
0 1 2 3 4

Front Rear
Insertion at Front

Front = -1
Rear = -1

0 1 2 3 4 5 6 7
Insertion at Front
Front = 0
Rear = 0

20
0 1 2 3 4 5 6 7

Front = 7
Rear = 0

20 30
0 1 2 3 4 5 6 7
Insertion at Front
Front = 6
Rear = 0

20 32 30
0 1 2 3 4 5 6 7

Front = 5
Rear = 0

20 11 32 30
0 1 2 3 4 5 6 7
Algorithm – Insertion At Front
1. START
2. IF F=0 && R = N-1 || F = R+1 THEN
PRINT “Overflow”
RETURN
3. IF F = -1 THEN
F= R = 0
ELSE IF F = 0 THEN
F= N-1
ELSE
F= F-1
END IF
Q[F] = Item
4. EXIT
Deletion at Front
Front = 5
Rear = 0

20 11 32 30
0 1 2 3 4 5 6 7

Front = 6
Rear = 0

20 32 30
0 1 2 3 4 5 6 7
Deletion at Front

Front = 6
Rear = 0

20 32 30
0 1 2 3 4 5 6 7

Front = 7
Rear = 0

20 30
0 1 2 3 4 5 6 7
Deletion at Front

Front = 0
Rear = 0

20
0 1 2 3 4 5 6 7
Algorithm – Deletion At Front
1. START
2. IF F=-1 THEN
PRINT “Underflow”
RETURN
3. Item = Q[F]
4. IF F = R THEN
F= R = -1
ELSE IF F = N-1 THEN
F= 0
ELSE
F= F+1
END IF
5. EXIT
Insertion at Rear
Front = -1
Rear = -1

0 1 2 3 4 5 6 7

Front = 0
Rear = 0

20
0 1 2 3 4 5 6 7
Insertion at Rear
Front = 0
Rear = 1

20 7
0 1 2 3 4 5 6 7

Front = 0
Rear = 2

20 7 13
0 1 2 3 4 5 6 7
Algorithm – Insertion At Rear
1. START
2. IF F=0 && R = N-1 || F = R+1 THEN
PRINT “Overflow”
RETURN
3. IF R = -1 THEN
F= R = 0
ELSE IF R = N-1 THEN
R= 0
ELSE
R= R+1
END IF
Q[R] = Item
4. EXIT
Deletion at Rear
Front = 0
Rear = 2

20 7 13
0 1 2 3 4 5 6 7

Front = 0
Rear = 1

20 7
0 1 2 3 4 5 6 7
Deletion at Rear
Front = 0
Rear = 0

20
0 1 2 3 4 5 6 7

Front = -1
Rear = -1

0 1 2 3 4 5 6 7
Algorithm – Deletion At Rear
1. START
2. IF R=-1 THEN
PRINT “Underflow”
RETURN
3. Item = Q[R]
4. IF F = R THEN
F= R = -1
ELSE IF R = 0 THEN
R= N-1
ELSE
R= R-1
END IF
5. EXIT
MID TERM
Linked Lists
Linked Lists
Elements of an array are stored sequentially in the memory. The sequential storage is not either possible
or efficient in larger computer systems
Array is static data structure. The size of array cannot be changed during the program execution

To overcome array limitation, linked lists are used.


• In linked lists, data is arranged into records, Each record is called a node.
• A data item may be stored anywhere in the memory.
• A special item, called pointer, is added to each record/node
• Pointer is used to contain a link to the next record.
• An item in the list is linked logically with the next item/record/node

There are two types of linked lists. There are:


• Single-linked lists or One-way lists
• Double-linked lists or Two-way lists
Pointers
Pointers
A pointer is a variable that is used to store memory address of another variable.
Each variable is created at a unique location in memory known as its address
Computer creates the variable at any available location in the memory
The memory address is a hexadecimal number that refers to a particular location in the memory

0x0064df0

The memory address is a hexadecimal number that refers to a particular location in the
memory

The use of pointer to link elements of a data structure implies that elements need not be
physically adjacent in the memory. They can be stored anywhere in the memory but they
logically remain adjacent. This type of storage is called linked storage.
Single Linked List
A single Linked list is a linear collection of data elements. The elements in a single linked list can be
visited starting from beginning and towards its end only in one direction

1010

1080 BSC 2090 MSC 3010 Mphil Null Phd

1010 1080 2090 3010

The Variable Start (called list pointer variable) contains the memory address of the first node of the list.
It points to starting memory location of the linked list. The linked list is accessed with reference to this
pointer variable.
Node has two parts
• One for actual value
• Second for next node address
Representation of Linked List in Memory
The storage technique of linked lists is different from that of linear arrays.
Each item of linked list contains at least two fields.
One field is used to store data and the other to store address of memory location of the next object.
In this way the objects of list are linked together in the form of a chain.
The following example explains this concept using C++ structure

struct node{
int data;
Node *link;
};
node *start;
Operation on Single Linked List
1. Traversing
2. Inserting
Add to Beginning
Add to End
Add to The middle
3. Deleting
Add to Beginning
Add to End
Add to The middle
Insertion

At the beginning

1000

1080 BSC 2090 MSC 3010 Mphil Null Phd

1010 1080 2090 3010

1010 FSC

1000
Insertion
At the beginning
struct node{
int data;
1. Allocate memory to new node
node *link;
2. Store data
};
3. Change next of new node to point to head
node *newNode = new node;
4. Change head to point recently created node
newNode -> data = 40;
newNode -> next = start;
start = newNode
Insertion

At the end

1010

1080 BSC 2090 MSC 3010 Mphil 3020 Phd

1010 1080 2090 3010

NULL Post
Phd
3020
Insertion
At the end
struct node{
int data;
1. Allocate memory to new node
node *link;
2. Store data
};
3. Traverse to last node
node *newNode = new node;
4. Change next of last node to recently created node
newNode -> data = 40;
newNode -> next = null;
node *temp = start;
while(temp->next !=null)
temp = temp->next
temp->next = newNode
Insertion

At the middle

1010

1080 BSC 3020 MSC 3010 Mphil Null Phd

1010 1080 2090 3010

3010 Post
Phd
3020
Insertion
At the middle
struct node{
int data;
1. Allocate memory to new node
node *link;
2. Store data
};
3. Traverse to node just before the position
node *newNode = new node;
4. Change the pointer to insert newnode between
newNode -> data = 40;
node *temp = start;
int pos, i;
for(i=2; i< pos ; i++){
if(temp -> next !=null)
temp = temp->next;
}
newNode -> next = temp->next;
temp->next = newnode;
Deletion
At the beginning
1080

1080 BSC 2090 MSC 3010 Mphil Null Phd

1010 1080 2090 3010


At the end
1010

1080 BSC 2090 MSC Null Mphil Null Phd

1010 1080 2090 3010


Deletion
At the middle
1080

2090 BSC 3010 Mphil Null Phd

1010 2090 3010

2090 MSC

1080
Deletion
At the middle
At the beginning
Traverse to element before the element to
Point head to second node deleted
head = head -> next Change next pointer
for(i=2; i<position; i++){
if(temp->next != null)
At the end temp = temp->next
Traverse to second last element }
Change its next pointer to null temp->next = tempt->next->next
node * temp = start
while(temp->next->next !=null
temp = temp->next
temp->next = Null
Algorithm _ Creating Linked List
1. DEFINE structure of node
2. DECLARE three pointer objects start, current & temp of type node
3. IF start =NULL
[Create first node and assign its address to “start”. Also assign value to the node]
start = new-node
start->data = data
start->link = NULL
4. ELSE
[Assign address of start node to the current node to proceed next]
current = start
while(current -> link != NULL)
Create new node
[Assign value and address of new node to current node and address of new-node to current]
temp = new-node
temp -> data = data
current->link = tem
5. Exit
Double Linked List
A linear list in which each node has the addresses each of next node and of the previous node is calle
double linked list. A double linked list can be visited in both directions, i.e. in forward and backward
direction. It is also called two-way list.
1010

1010 MSC 2090 1080 MPhil NULL


NULL 1080 BSC

1010 1080 2090

The Variable Start (called list pointer variable) contains the memory address of the first node of the list.
It points to starting memory location of the linked list. The linked list is accessed with reference to this
pointer variable.
Node has three parts
• One for actual value
• Second for next node address
• Third for previous node address
Representation of Double Linked List
The double-linked list is represented in the memory as a data structure having at least three fields. In
C++, it is defined as:

struct node{
node * previous;
int data;
node * next;
} *start, *pn, *temp
Algorithm – Creating Double–Linked List
Write a algorithm to create a double-linked list consisting of ten nodes.
Suppose X is data field of the node and p & n are its pointer fields for previous and next nodes,
respectively
1. REPEAT Step-2 For C=1 to 10
2. temp = new node
IF C =1 Then
Start = temp
Start -> p = Null
Start -> X = Value
Start -> n = Null
pn = temp
Else
pn -> n = temp
temp -> p = pn
temp ->X = Value
pn= temp
3. Exit
Double-Linked List Operations
Like single-linked lists, the following operations can be performed on the double linked list.
● Traversing
○ Forward Direction
○ Backward Direction
● Insertion
○ At Begin
○ At Middle
○ At End
● Deletion
○ At Begin
○ At Middle
○ At End
Traverse double Linked List
Forward
Start from head/start pointer
visit all nodes by referencing and access node data

Reverse
Start from head/start pointer
visit all nodes by referring and reach last node
Access node data by referring all nodes in reverse direction

1010

1010 MSC 2090 1080 MPhil NULL


NULL BSC 1080

1010 1080 2090


Insertion
At the beginning At the middle
Traverse to element before the element to
1. Allocate memory to new node deleted
2. Store data Change next pointer
3. Change next of new node to point to head for(i=2; i<position; i++){
4. Change head to point recently created node if(temp->next != null)
5. Change prev of Previous first node to new temp = temp->next
node reference }
At the end temp->next = tempt->next->next
temp->next->prev = temp
1. Allocate memory to new node
2. Store data
3. Traverse to last node
4. Change next of last node to recently created node
5. Change Prev of new node to previously traversed
last node
Deletion
At the middle
At the beginning
Traverse to element before the element to
Point head to second node deleted
head = head -> next Change next pointer
head->next->prev = Null for(i=2; i<position; i++){
if(temp->next != null)
At the end temp = temp->next
Traverse to second last element }
Change its next pointer to null temp->next = tempt->next->next
node * temp = start temp->next->prev = temp
while(temp->next->next !=null
temp = temp->next
temp->next = Null
Tree
Tree
Tree is a non-linear data structure. This is used to represent hierarchical relationship
between elements.
A tree is a finite set of node with finite set of edge that define parent-child relationship and
there are no circuit.

Properties:

● There are only one root having no parent


● Each node has exactly one parent
● A node may have zero or more children
● There are unique path from root to each node
Tree Terminology
Root: The node at the top of the tree is called the node. There is only one root in a tree. The
root node is the starting point of a tree. It does not have a parent node. However, it may have
as many child nodes as desired.

Edge: Edge is a connection between one node to another. The line drawn from a parent
node to its child node is called an edge.

Path: Path is a number of successive edges from source node to destination node.

Parent: The node above a node (or immediate predecessor of a node) is called the parent of
that node.
Tree Terminology
Child: The nodes that are directly linked in a node one level above them (or immediate
successors of a node) are called child nodes or children to the parent node.

Siblings: The nodes that share a parent node are a set of sibling nodes.

Degree: Degree of a node is equal to the number of its child nodes.

Leaf: A node that has no children is called leaf node or a leaf. These are also called leaf
nodes.

Subtree: A set of all nodes that consists of any node (except the root) and all nodes below that
node is called subtree.
Tree Terminology
Levels: The level of a particular node refers to its position in the tree. The root node is the top
level node and can be referred as level 0. The children are at level 1 and grandchildren at level
2 and so on.

Depth of Node: Depth of a node represents the number of edges from the tree’s root node to
that node.

Height of Node: Height of a node is the number of edges on the longest path between that
node and a leaf.

Height of tree: Height of tree is the height of its root node.

Empty tree: A tree that contains no node is called an empty tree.


Tree Terminology
Tree Terminology
A Non-Tree
● In valid tree, there must be one path from the root to any other node.
● In a valid tree for N nodes there should be N-1 Edges/Links

Example of a non-tree
Binary Tree
A binary tree is a tree-type non-linear data structure with a maximum of two children for each
parent. Every node in a binary tree has a left and right reference along with the data element.
The node at the top of the hierarchy of a tree is called the root node.

Each node in a binary tree has these three elements


● Data item that is the data stored in the node
● Address of the left child
● Address of the right child
Binary Tree
struct Node { Node *newNode(int data) {
int data; //allocating space for the node
struct node *left; Node *node = new Node;
struct node *right;
}; //storing in the data
node->data = data;
//setting left and right children to NULL
node->left = NULL;
node->right = NULL;
return (node);
}
Types of Binary Tree in Data
Structure
Full Binary Tree
A full binary tree, also known as a proper binary tree, is a tree in which each internal node has
either zero or two children nodes is known as a full binary tree.

In other words, if in a binary tree a node contains only one child node, it is not a full binary tree.
Complete Binary Tree
In a complete binary tree

● All the levels are completely filled except the last level that may or may not be completely
filled.
● Elements are filled from left to right.
Perfect Binary Trees
If in a tree all the internal nodes have exactly two children nodes, it is known as a perfect binary
tree
In a perfect binary tree, all the leaf nodes are on the same level.
Degenerate Binary Trees
If in a binary tree each node contains only one child node either on the left side or the right side
of the tree, it is known as a degenerate binary tree.

Degenerate binary trees are equal to linked lists in terms of performance.

Left-skewed Right-skewed
Balanced Binary Trees
A binary tree is said to be balanced if the height of the left and the right subtrees differ by 0 or
1.

In a balanced binary tree, both the left and right trees are also balanced.
Traversing Binary Tree using Iteration
1. Preorder (Node - Left - Right)
2. Inorder (Left - Node - Right)
3. Postorder (Left - Right - Node)

Preorder Inorder Postorder

1. Process the Root R 1. Traverse the left 1. Traverse the left


2. Traverse the left subtree of R in preorder subtree of R in preorder
subtree of R in preorder 2. Process the Root R 2. Traverse the Right
3. Traverse the Right 3. Traverse the Right subtree of R in preorder
subtree of R in preorder subtree of R in preorder 3. Process the Root R
Preorder Traversing Binary tree Using Stack
1. Proceed down to left most path, processing each node N on path and push each right child
on to stack. The traversing end after a node N with no left child proceed
2. Pop top element on stack, then return to step(1) of stack is empty

Push Pop
A
B C

D E F

G
Inorder Traversing Binary tree Using Stack
1. Proceed down to left most path push each node N on the stack. Stop when node n with no
left child pushed onto stack.
2. Pop and Process the node on stack Push Pop
a. If null is popped exit
b. if a node N with Right child is processed and repeat step 1

A
B C

D E F

G
Postorder Traversing Binary tree Using Stack
1. Proceed down to left most path pushing each node on stack if N has a Right child push
“-Rightchild”
2. Pop and Process positive node on stack Push Pop
a. if negative node is popped, repeat step 1
b. if Null is popped exit

A
B C

D E F

G
Binary Search Tree
Binary Search tree every node is organised in specific order. This is also called ordered Binary
tree
Suppose T is Binary Tree then T is called (BST) if each node of T has following properties
The value of N is greater than every value in left subtree
The Value of N is less than every value in Right subtree of N. 38

14 56

82
8
23 45

70
18
Binary Search Tree Operations
Operations: 1. Compare ITEM with Root node N
a. if ITEM<N Proceed to left child
1. Search b. If ITEM>N Proceed to Right child
2. Insert 2. Repeat step 1 until one of following occur\
3. Delete a. We meet a node N such that ITEM==N
b. We meet a empty subtree which include
unsuccessful and Insert item at empty
38 location

14
56

8 23 45 82

18 70
Binary Search Tree Operations
Delete Case 1: Node is leaf node
Operation Case 2: Node has only child
Case 3: Noe has two child

38

14
56

8 23 45 82

18 70
AVL Tree
AVL Tree can be defined as height balance binary search tree in which each node is associated
with Balance Factor (BF) 0, 1, -1.

Balance Factor = height left subtree - height of right subtree

BF = 1 38 BF = 2
38

BF = -1 14 56
BF = -1 14 56

82 8
8 45
23 45 23

70
18 18
AVL Tree
Rotation:
1. Left - left Rotation (LL-Rotation)
2. Right- Right Rotation (RR-Rotation)
3. Left - Right Rotation (LR-Rotation)
4. Right - left Rotation (RL-Rotation)
38 BF = 2

38 BF = 2
14 56

14
8
23 45

8
18
AVL Tree Insertion
Construct the AVL search tree by Inserting the following element
64, 1, 14, 26, 13, 110, 98, 85

14

1 64

98
13 26
110
85
AVL Tree Deletion
30
Deletion is similar as binary search tree. After deletion we reconstruction the tree
if needed to maintain it height.
20 40
Step 1: Find element in the tree
Step2: Delete the node as BST Rule
Step 3: Two case are possible if tree is unbalanced.
Case 1: Deletion from Right subtree 10
i) if BF(N) = +2 and BF(N -> LC)= +1, do LL Rotation
ii) if BF(N) = +2 and BF(N->LC)= -1, do LR Rotation 30
iii) if BF(N) = +2 and BF(N -> LC)=0, do LL Rotation
Case 2: Deletion from :Left subtree
i) if BF(N) = -2 and BF(N -> RC)= -1, do RR Rotation 20
ii) if BF(N) = -2 and BF(N->RC)= +1, do RL Rotation 40
iii) if BF(N) = -2 and BF(N -> RC)=0, do RR Rotation

50
Graph
Graphs
Graphs are non-linear data structures. A graph is made up of sets of nodes and lines. Nodes
are called vertices. Lines are called edges. Lines are used to connect nodes. An edge of the
graph is represented as:

e = [u, v]

‘u’ and ‘v’ denote the start and end nodes of edge ‘e’, respectively. They are also known as
the tail and head nodes of edge ‘e’.

LAHORE KARACHI

ISLAMABAD
SAHIWAL

FAISALABAD
Graphs
Undirected Graphs
An undirected graph has edges that have no direction. An undirected graph is also called
an undigraph.

Directed Graphs
A direct graph has edges that are unidirectional. A directed graph is also called a digraph.

Weighted Graphs
A graph which has a weight, or number, associated with each edge is called weighted
graph.

Degree of Node
The number of edges that a node contain is called degree of the node.
Graphs
Out-degree & In-degree
The number of edges beginning from a node is called the out-degree of the node. The
number of edges at a node is called the In-degree of the node.

Total degree of the node = in-degree + out-degree A E

C D
Path & Length of Graph
A list of nodes of a graph where each node has an edge from it to the next node is called
the path.

Loop Edge
An edge ‘e’ is said to be a loop edge if it has the same node at its tail and head.
Representation of Graphs
Graphs are unstructured. One vertex in a graph might be adjacent to every other vertex. The
adjacency list is used to represent the graph in memory.

Adjacency List
An adjacency list is array of listed lists, on for each vertex. Each linked list contains all of
the vertices that are adjacent to a given vertex.

A E

C D
Adjacency List

A E B
A E
B C
B
C D E

D E
C D
E
Depth-First Search
In Depth First Search (DFS), the search can be started from any vertex in the graph
Algorithm – DFS
1. Visiting first node and its neighbors along the path p of a graph
2. Set the status of all nodes to ready state
3. Push the starting node A onto the stack and set its status to the waiting state.
4. Repeat step-5 to 6 until stack is empty
5. Pop the top node of stack, process it and set its status to process state.
6. Push all the neighbour of A onto the stack that have status of ready state and set their
status to the waiting state.
[End of loop at step-4]
A E
7. Exit
B

C D
Breadth-First Search
In Breadth – First Search (BFS)
1. Visiting first node and its neighbours of a graph
2. Set the status of all nodes to ready state
3. Put the starting node A into the queue and set its status to the waiting state.
4. Repeat step-5 to 6 until queue is empty
5. Pick the front node of queue, process it and set its status to processed state.
6. Add all the neighbours of A into the queue that have status of ready state and set their
status to the waiting state.
[End of loop at step-4]
7. Exit
A E

C D
Breadth-First Search

A E

B F

C D
G

You might also like