Chapter-1
Chapter-1
Floating Pointers
Point Linear Non-linear
List List
Array
File
List
Linear / Non-Linear data structure
Linear data structures
A data structure is said to be Linear, if its elements are connected in linear fashion by means of
logically or in sequence memory locations.
Examples of Linear Data Structure are Stack and Queue.
Sometimes, we can have more than one algorithm for the same problem to process a data structure, and
we have to choose the best one among available algorithms for example, a sorting problem has many
algorithms, like insertion sort, selection sort, quick sort and many more . This is done by algorithm
analysis.
“The best algorithm is the one which has a fine balance between time taken and
memory consumption.”
Introduction of Algorithm
Algorithm analysis helps us to determine which algorithm is most efficient in terms of
time and space consumed.
• In order to simplify the process of complex problem solving, user defined data types are used,
which are the combination of data structures with their operations, and we call this Abstract Data
Type or ADT.
• Most commonly used ADTs are : Linked Lists, Array, Stacks, Queues, Priority Queues, Trees etc.
Outline
Looping
Array
• Representation of arrays
• One dimensional array
• Two dimensional array
Applications of arrays
• Symbol Manipulation (matrix representation of polynomial
equation)
• Sparse matrix
Sparse matrix and its representation
What is an Array?
What is an array?
First and most basic data structure, once array is created one memory block
is blocked. Elements of array are accessed in constant time using index value
of the array.
• Why constant time for accessing array element?
One Dimensional Array
Simplest data structure that makes use of computed address to locate its elements is
the one-dimensional array or vector.
Number of memory locations is sequentially allocated to the vector.
A vector size is fixed and therefore requires a fixed number of memory locations.
Vector A with subscript lower bound of “one” is represented as below….
L0 • L0 is the address of the first word allocated to the first element of vector A
i-1 • C words is size of each element or node
• The address of element Ai is
L0+(i-1)C
Loc(Ai) = L0 + (C*(i-1))
A[i] • Let’s consider the more general case of a vector A with lower bound for it’s
subscript is given by some variable b.
• The address of element Ai is
Loc(Ai) = L0 + (C*(i-b))
Example:
Example: Address Calculation for a Vector
Given:
1. Base Address (L0): 1000 (assume in memory
units).
2. Size of Each Element (C): 4 words.
3. Lower Bound of Subscript (b): 3.
Find: The address of the element A6 Loc(A6)=1000+(4⋅(6−3)) = 1012
Two Dimensional Array
Two dimensional arrays are also called table or matrix
Two dimensional arrays have two subscripts
Column major order matrix: Two dimensional array in which elements are stored
column by column is called as column major matrix
Two dimensional array consisting of two rows and four columns is stored sequentially
by columns : A[1,1], A[2,1],A[1,2], A[2,2], A[1,3],A[2,3], A[1,4], A[2,4]
Column - 5
Column - 7
Column - 6
Column - 4
Column - 1
Column - 2
Row - 1 0 0 0 2 0 0 1 0 Terms 0 1 2 3 4 5 6 7 8
Row 1 1 2 2 2 3 3 4 4
Row - 2 0 6 0 0 7 0 0 3
Column 4 7 2 5 8 4 6 2 3
Row - 3 0 0 0 9 0 8 0 0 Value 2 1 6 7 3 9 8 4 5
Row - 4 0 4 5 0 0 0 0 0
Linear Representation of given matrix
4x8
Sparse matrix Cont…
To construct matrix structure from liner representation we need to record.
Original row and columns of each non zero entries.
Number of rows and columns in the matrix.
So each element of the array into which the sparse matrix is mapped need to have three
fields: row, column and value
Sparse matrix Cont…
1 2 3 4 5 6 7
Linear representation of Matrix
1 0 0 6 0 9 0 0
Row Column A
2 2 0 0 7 8 0 4
1 3 6
A= 3 10 0 0 0 0 0 0
4 0 0 12 0 0 0 0 1 5 9
5 0 0 0 0 0 0 0 2 1 2
6 0 0 0 3 0 0 5 2 4 7
6x7
2 5 8
Memory Space required to store 4
2 7
6x7 matrix
3 1 10
42 x 4 = 168 bytes
4 3 12
6 4 3
Memory Space required to store
6 7 5
Linear Representation
Declaration
int rollno;
An array is a fixed size sequential collection of elements of same data type grouped under
single variable name.
Program Row-0 1 2 3
1 void main(){ Row-1 4 5 6
2 int data[3][3],i,j;
3 for(i=0;i<3;i++) Row-2 7 8 9
4 {
5 for(j=0;j<3;j++)
6 { Output
7 printf("Enter array element="); Enter array element=1
8 scanf("%d",&data[i][j]); Enter array element=2
9 } Enter array element=3
10 } Enter array element=4
11 for(i=0;i<3;i++) Enter array element=5
12 { Enter array element=6
13 for(j=0;j<3;j++) Enter array element=7
14 { Enter array element=8
15 printf("%d",data[i][j]); Enter array element=9
16 } 123
17 printf("\n"); 456
18 } 789
19 }
Definition: String
Each character in the array occupies one byte of memory, and the last character must always
be null('\0').
The termination character ('\0') is important in a string to identify where the string ends.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10] T H A P A R \0
Declaring & Initializing String
Declaration
char name[10];
Initialization method 1:
char name[10]={‘T',’H',’A',’P',’A',’R','\0'};
Initialization method 2:
char name[10]=“THAPAR";
//'\0' will be automatically inserted at the end in this type of declaration.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10] T H A P A R \0
Read String: scanf()
Program
Output
1 void main()
2 { Enter name: Thapar
3 char name[10]; Name=Thapar
4 printf("Enter name:"); Output
5 scanf("%s",name);
Enter name: ECE Thapar
6 printf("Name=%s",name);
Name=ECE
7 }
gets(): Reads characters from the standard input and stores them as a string.
puts(): Prints characters from the standard.
scanf(): Reads input until it encounters whitespace, newline or End Of File(EOF)
whereas gets() reads input until it encounters newline or End Of File(EOF).
gets(): Does not stop reading input when it encounters whitespace instead it takes
whitespace as a string.
Format specifiers in C
Format
Data Type Size (Bytes) Example
Specifier
%c char 1 'A'
%s char[] (string) Varies (depends on Hello (6 bytes including \0)
string length)
%f float 4 3.14
%e float (scientific 4 1.23e+04
notation)
%lf double 8 3.141592654
References and
Memory Address
strchr(string1, ch): Searches for the first occurrence of character ch in string1. Returns a
pointer to the character if found, otherwise returns nullptr.
strstr(string1, string2): Searches for the first occurrence of the substring string2 in string1.
Returns a pointer to the substring if found, otherwise returns nullptr.
Example
// Declaring C-style strings
char string1[100] = "Hello";
char string2[] = "World";
1. strcpy(string1, string2); cout << "After strcpy: " << string1 << endl;
2. strcat(string1, " ");
strcat(string1, string2); cout << "After strcat: " << string1 << endl;
3. strlen(string1);
4. strcmp(string1, string2);
5. strchr(string1, 'o’);
1. After strcpy: World
6. strstr(string1, "lo"); 2. After strcat: World World
3. Length of string1: 11
4. string1 is greater than string2.
5. First occurrence of 'o' in string1: o World
6. Substring 'lo' found in string1: lo World
Basic C++ code for string
#include <iostream> void display() {
cout << "Name: " << name << endl;
#include <string>
cout << "Email: " << email << endl;
using namespace std; }
class Person { };
int main() {
private: Person person;
string name; // Taking input from user
person.getInput();
string email; // Displaying the entered details
public: person.display();
return 0;
void getInput() { }
cout << "Enter name: ";
getline(cin, name); Output:
cout << "Enter email: "; Enter name: Ankit Soni
Enter email: ankit12@gmail.com
getline(cin, email); Name: Ankit Soni
} Email: ankit12@gmail.com
C++ REFERENCES
we have read that C++ supports two types of variables:
An ordinary variable is a variable that contains the value of some type. For example, we create
a variable of type int, which means that the variable can hold the value of type integer.
A pointer is a variable that stores the address of another variable. It can be dereferenced to
retrieve the value to which this pointer points to.
There is another variable that C++ supports, i.e., references. It is a variable that behaves as an
alias for another variable.
HOW TO CREATE A REFERENCE?
Reference can be created by simply using an ampersand (&) operator. When we create a
variable, then it occupies some memory location. We can create a reference of the variable;
therefore, we can access the original variable by using either name of the variable or reference.
For example,
int a=10;
Now, we create the reference variable of the above variable.
int &ref=a;
The above statement means that 'ref' is a reference variable of 'a', i.e., we can use the 'ref'
variable in place of 'a' variable.
A Reference Must Be Initialized
#include <iostream>
using namespace std;
int main() {
int num = 10;
int &ref;
cout << "Original value: " << num << endl;
cout << "Reference value: " << ref << endl;
return 0;
}
Output:
Error
References to non-const values
#include <iostream>
using namespace std;
int main() {
int num = 10;
int &ref = num; // Creating a reference to num
cout << "Original value: " << num << endl;
cout << "Reference value: " << ref << endl;
return 0;
}
Output:
Original value: 10
Reference value: 10
References to non-const values
#include <iostream>
using namespace std;
int main() {
int num = 10;
int &ref1 = num; // Creating a reference1 to num
int &ref2 = ref1; // Creating a reference2 to num
int &ref3 = ref2; // Creating a reference3 to num
cout << "Original value: " << num << endl;
cout << "Reference value1: " << ref1 << endl; Output:
cout << "Reference value2: " << ref2 << endl; Original value: 10
cout << "Reference value3: " << ref3 << endl; Reference value1: 10
return 0; Reference value2: 10
} Reference value3: 10
A Reference Cannot Be Null
#include <iostream>
using namespace std;
int main() {
int num = 10;
int &ref = nullptr;
cout << "Original value: " << num << endl;
cout << "Reference value: " << ref << endl;
return 0;
}
Output:
Error
A Reference pointer Can Be Null
#include <iostream>
using namespace std;
int main() {
int num = 10;
int *ref = nullptr;
cout << "Original value: " << num << endl;
cout << "Reference value: " << ref << endl;
return 0;
}
Output:
10
0
A Reference Cannot Be Reassigned
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
int &ref = a; Output:
ref = b; Error
ref = &b;
cout << "Original value-a: " << a << endl;
cout << "Original value-b: " << b << endl;
cout << "reference value-ref:" << a << endl;
return 0;
}
A Reference Is Just an Alias
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
int &ref = a; Output:
ref = b; Original value-a: 20
cout << "Original value-a: " << a << endl;
Original value-b: 20
reference value-ref:20
cout << "Original value-b: " << b << endl;
cout << "reference value-ref:" << a << endl;
return 0;
}
A Reference Cannot Be Declared Without a Type
int main() {
int x = 10; double y = 20.5;
int &ref1 = x;
double &ref2 = y;
int &ref3 = y; Output:
cout << "x: " << x << endl; Error
cout << "y: " << y << endl;
cout << "ref1:" << ref1 << endl;
cout << "ref2:" << ref2 << endl;
cout << "ref3:" << ref3 << endl;
return 0;
}
A Reference Is Just an Alias
int main() {
int x = 10; double y = 20.5;
int &ref1 = x;
double &ref2 = y;
double &ref3 = y; Output:
cout << "x: " << x << endl; x: 10
cout << "y: " << y << endl;
y: 20.5
ref1:10
cout << "ref1:" << ref1 << endl;
ref2:20.5
cout << "ref2:" << ref2 << endl;
ref3:20.5
cout << "ref3:" << ref3 << endl;
return 0;
}
Reference variable
You cannot create a reference to an array directly, but you can reference individual elements
int arr[3] = {1, 2, 3};
int &ref = arr[0]; // Correct: Refers to the first element of the array
}
Nullptr Represents a Null Address
#include <iostream>
using namespace std;
int main() {
int *ptr = nullptr; // Pointer is null
if (ptr == nullptr)
cout << "Pointer is null." << endl;
return 0; Output:
Pointer is null.
}
Void Pointers Can Store Any Address
#include <iostream>
using namespace std;
int main() {
int x = 100;
void *ptr = &x; // Void pointer holding address of x
cout << "Address stored in void pointer: " << ptr << endl;
cout << "Value of x (using typecasting): " << *(int *)ptr << endl;
return 0;
}
Output:
Address stored in void pointer: 0x7ffee59c2a3c
Value of x (using typecasting): 100
Linked List
Why Linked lists ?
Array:
?
1) Static size
2) Expensive to Insertion or deletion of New elements in array.
One method of obtaining the address of node is to store address in computer’s main memory,
we refer this addressing mode as pointer of link addressing.
A simple way to represent a linear list is to expand each node to contain a link or pointer to the
next node. This representation is called one-way chain or Singly Linked Linear List.
Linked Storage Representation
NULL
Last Node Value
A 1000 B 2050 C 3335 D
5000 1000 2050 3335
A linked List
The linked allocation method of storage can result in both efficient use of computer storage
and computer time.
A linked list is a non-sequential collection of data items.
Each node is divided into two parts, the first part represents the information of the element and the second
part contains the address of the next mode.
The last node of the list does not have successor node, so null value is stored as the address.
It is possible for a list to have no nodes at all, such a list is called empty list.
Pros & Cons of Linked Allocation
Insertion Operation
We have an n elements in list and it is required to insert a new element between the first and second element,
what to do with sequential allocation & linked allocation?
Insertion operation is more efficient in Linked allocation.
X 1000
2100
Pros & Cons of Linked Allocation
Deletion Operation
Deletion operation is more efficient in Linked Allocation
Join Operation
Join operation is more efficient in Linked Allocation.
Linked list require more memory compared to array because along with value it stores pointer
to next node.
Linked lists are among the simplest and most common data structures. They can be used to
implement other data structures like stacks, queues, and symbolic expressions, etc…
Operations & Type of Linked List
Operations on Linked List Types of Linked List
Insert Singly Linked List
• Insert at first position Circular Linked List
• Insert at last position Doubly Linked List
• Insert into ordered list
Delete
Traverse list (Print list)
Copy linked list
Singly Linked List
Info Link
Accessing Part
Node
of Node
Typical Node Info (Node)
Data Pointer to Link (Node)
Next Node
struct node
{
C Structure to int info;
represent a node struct node *link;
};
Algorithms for singly linked list
1. Insert at first position
2. Insert at last position
3. Insert in Ordered Linked list
4. Delete Element
Availability Stack
A pool or list of free nodes, which we refer to as the availability stack is maintained in
conjunction with linked allocation.
Whenever a node is to be inserted in a list, a free node is taken from the availability stack and
linked to the new list.
On other end, the deleted node from the list is added to the availability stack.
5. [Is the list empty?] 8. [Set link field of last node to NEW]
If FIRST = NULL LINK (SAVE) NEW
Then Return (NEW)
9. [Return first node pointer]
6. [Initialize search for a last node] Return (FIRST)
SAVE FIRST
SAVE
10 50 -1 8 35 44 50
NEW
FIRST
Function: INSEND(50, FIRST)
4. [Initialize fields of new node] 7. [Search for end of list]
INFO(NEW) X Repeat while LINK (SAVE) ≠ NULL
LINK (NEW) NULL SAVE LINK (SAVE)
5. [Is the list empty?] 8. [Set link field of last node to NEW]
If FIRST = NULL LINK (SAVE) NEW
Then Return (NEW)
9. [Return first node pointer]
6. [Initialize search for a last node] Return (FIRST)
SAVE FIRST
SAVE
10 50 -1 8 35 44 50
NEW
FIRST
Single Linked List
// Define the structure for a node // Function to handle stack underflow
struct Node { void handleUnderflow() {
int data; // INFO(NEW) if (avail == nullptr) { // If AVAIL = NULL
Node* link; // LINK(NEW) cout << "Underflow" << endl;
}; return;
// Initialize pointers for the linked list }
Node* avail = nullptr; // Availability stack }
pointer (AVAIL)
Node* first = nullptr; // First node in the list
(FIRST)
Single Linked List
Node* createNode(int x) { if (first == nullptr) {
handleUnderflow(); // Step 1: Check underflow first = newNode; // Set new node as FIRST
return first;
if (avail == nullptr) return first; // Return FIRST if
}
no node available // Step 6: Initialize search for the last node
// Step 2: Obtain address of next free node Node* save = first;
Node* newNode = avail; // Step 7: Search for the end of the list
// Step 3: Remove free node from availability stack while (save->link != nullptr) {
save = save->link;
avail = avail->link; }
// Step 4: Initialize fields of new node
// Step 8: Set link field of the last node to NEW
newNode->data = x; save->link = newNode;
newNode->link = nullptr;
// Step 9: Return the FIRST node pointer
// Step 5: Check if the list is empty return first;
}
Single Linked List
// Function to display the linked list
void displayList(Node* head) {
Node* current = head;
while (current != nullptr) {
cout << current->data << " -> ";
current = current->link;
}
cout << "NULL" << endl;
}
Single Linked List
int main() {
// Insertvalues into the linked list
// Example: Initialize the first = createNode(10);
availability stack with some nodes first = createNode(20);
first = createNode(30);
avail = new Node{0, nullptr}; //
Predefined nodes for the availability
// Display the linked list
stack cout << "Linked List: ";
avail->link = new Node{0, nullptr}; // displayList(first);
Adding one more node
return 0;
}
5 10 15 20 25 30
FIRST
22
NEW
Function: INSORD(X, FIRST)
This function inserts a new node such that linked list preserves the ordering of the terms in
increasing order of their INFO field.
This function returns address of FIRST node.
X is a new element to be inserted.
FIRST is a pointer to the first element of a Singly linked linear list.
Typical node contains INFO and LINK fields.
AVAIL is a pointer to the top element of the availability stack.
NEW is a temporary pointer variable. Predecessor
5 10 15 20 25 30
FIRST
22
NEW
Function: INSORD(X, FIRST)
1. [Underflow?] 6. [Does the new node precede all other
IF AVAIL = NULL node in the list?]
THEN Write (“Availability IF INFO(NEW) ≤ INFO (FIRST)
Stack Underflow”) THEN LINK (NEW) FIRST
Return(FIRST) Return (NEW)
2. [Obtain address of next free Node] 7. [Initialize temporary pointer]
NEW AVAIL SAVE FIRST
3. [Remove free node from availability 8. [Search for predecessor of new node]
Stack] Repeat while LINK (SAVE) ≠ NULL
AVAIL LINK(AVAIL) & INFO(NEW) ≥ INFO(LINK(SAVE))
4. [Initialize fields of new node] SAVE LINK (SAVE)
INFO(NEW) X 9. [Set link field of NEW node and its
5. [Is the list empty?] predecessor]
IF FIRST = NULL LINK (NEW) LINK (SAVE)
THEN LINK(NEW) NULL LINK (SAVE) NEW
Return (NEW) 10. [Return first node pointer]
Return (FIRST)
Function: INSORD(3, FIRST)
5 10 15 20 25 30
FIRST
3
NEW
6. [Does the new node precede all other node in the list?]
IF INFO(NEW) ≤ INFO (FIRST)
THEN LINK (NEW) FIRST
Return (NEW)
Function: INSORD(22, FIRST)
7. [Initialize temporary pointer] 9. [Set link field of NEW node and its
SAVE FIRST predecessor]
8. [Search for predecessor of new node] LINK (NEW) LINK (SAVE)
Repeat while LINK (SAVE) ≠ NULL LINK (SAVE) NEW
& INFO(NEW) ≥ INFO(LINK(SAVE)) 10. [Return first node pointer]
SAVE LINK (SAVE) Return (FIRST)
SAVE
5 10 15 20 25 30
FIRST
22
NEW
Function: INSORD(22, FIRST)
7. [Initialize temporary pointer] 9. [Set link field of NEW node and its
SAVE FIRST predecessor]
8. [Search for predecessor of new node] LINK (NEW) LINK (SAVE)
Repeat while LINK (SAVE) ≠ NULL LINK (SAVE) NEW
& INFO(NEW) ≥ INFO(LINK(SAVE)) 10. [Return first node pointer]
SAVE LINK (SAVE) Return (FIRST)
SAVE
5 10 15 20 25 30
FIRST
22
NEW
Procedure: DELETE(X, FIRST)
This algorithm delete a node whose address is given by variable X.
FIRST is a pointer to the first element of a Singly linked linear list.
Typical node contains INFO and LINK fields.
SAVE & PRED are temporary pointer variable.
PRED SAVE
5 10 15 20 25 30
FIRST
Procedure: DELETE(X, FIRST)
This algorithm delete a node whose address is given by variable X.
FIRST is a pointer to the first element of a Singly linked linear list.
Typical node contains INFO and LINK fields.
SAVE & PRED are temporary pointer variable.
PRED
5 10 15 25 30
FIRST
Procedure: DELETE( X, FIRST)
1. [Is Empty list?] 5. [Move to next node]
IF FIRST = NULL SAVE LINK(SAVE)
THEN write (‘Underflow’) 6. [End of the list?]
Return If SAVE ≠ X
2. [Initialize search for X] THEN write (‘Node not found’)
SAVE FIRST Return
3. [Find X] 7. [Delete X]
Repeat thru step-5 If X = FIRST
while SAVE ≠ X and THEN FIRST LINK(FIRST)
LINK (SAVE) ≠ NULL ELSE LINK (PRED) LINK (X)
4. [Update predecessor marker] 8. [Free Deleted Node]
PRED SAVE Free (X)
Procedure: DELETE(7541, FIRST)
2. [Initialize search for X] 6. [End of the list?]
SAVE FIRST If SAVE ≠ X
3. [Find X] THEN Write (‘Node not found’)
Repeat thru step-5 Return
while SAVE ≠ X and 7. [Delete X]
LINK (SAVE) ≠ NULL If X = FIRST
4. [Update predecessor marker] THEN FIRST LINK(FIRST)
PRED SAVE ELSE LINK (PRED) LINK (X)
5. [Move to next node] 8. [Free Deleted Node]
SAVE LINK(SAVE) Free (X)
SAVE
PRED
5 10 15 20 25 30
4455 8564 7541 1254 3254
5000
FIRST
Procedure: DELETE(7541, FIRST)
2. [Initialize search for X] 6. [End of the list?]
SAVE FIRST If SAVE ≠ X
3. [Find X] THEN Write (‘Node not found’)
Repeat thru step-5 Return
while SAVE ≠ X and 7. [Delete X]
LINK (SAVE) ≠ NULL If X = FIRST
4. [Update predecessor marker] THEN FIRST LINK(FIRST)
PRED SAVE ELSE LINK (PRED) LINK (X)
5. [Move to next node] 8. [Free Deleted Node]
SAVE LINK(SAVE) Free (X)
SAVE
PRED
5 10 15 25 30
4455 8564 1254 3254
5000
FIRST
Function: COUNT_NODES(FIRST)
This function counts number of nodes of the linked list and returns COUNT.
FIRST is a pointer to the first element of a Singly linked linear list.
Typical node contains INFO and LINK fields.
SAVE is a Temporary pointer variable.
5 10 15 20 25 30
FIRST
Circularly Linked Linear List Cont…
Disadvantages of Circular List
It is not easy to reverse the linked list.
If proper care is not taken, then the problem of infinite loop can occur.
If we at a node and go back to the previous node, then we can not do it in single step. Instead we have to
complete the entire circle by going through the in between nodes and then we will reach the required node.
50
NEW 5 10 1 -5
FIRST
Procedure: CIR_INS_FIRST(X,FIRST,LAST)
1. [Creates a new empty node] IF FIRST = NULL
NEW NODE THEN LINK (NEW) NEW
2. [Initialize fields of new node and FIRST LAST NEW
its link] ELSE LINK (NEW) FIRST
INFO (NEW) X LINK (LAST) NEW
FIRST NEW
FIRST
Return
NEW
FIRST LAST
50
LAST
50
NEW 5 10 1 -5
Procedure: CIR_INS_LAST(X,FIRST,LAST)
This procedure inserts a new node at the last position of Circular linked list.
X is a new element to be inserted.
FIRST and LAST are a pointer to the first & last elements of a Circular linked linear list,
respectively.
Typical node contains INFO and LINK fields.
NEW is a temporary pointer variable.
Procedure: CIR_INS_LAST( X,FIRST,LAST)
1. [Creates a new empty node] IF FIRST = NULL
NEW NODE THEN LINK (NEW) NEW
2. [Initialize fields of new node FIRST LAST NEW
and its link] ELSE LINK (NEW) FIRST
INFO (NEW) X LINK (LAST) NEW
LAST NEW
Return
NEW
FIRST LAST
50
LAST
50
NEW
5 10 1 -5
FIRST
Procedure: CIR_INS_LAST( X,FIRST,LAST)
1. [Creates a new empty node] IF FIRST = NULL
NEW NODE THEN LINK (NEW) NEW
2. [Initialize fields of new node FIRST LAST NEW
and its link] ELSE LINK (NEW) FIRST
INFO (NEW) X LINK (LAST) NEW
LAST NEW
Return
LAST
NEW
FIRST LAST
50
50
NEW
5 10 1 -5
FIRST
Procedure: CIR_INS_ORD(X,FIRST,LAST)
This function inserts a new node such that linked list preserves the ordering of the terms in
increasing order of their INFO field.
X is a new element to be inserted.
FIRST and LAST are a pointer to the first & last elements of a Circular linked linear list,
respectively.
Typical node contains INFO and LINK fields.
NEW is a temporary pointer variable.
Procedure: CIR_INS_ORD(X,FIRST,LAST)
1. [Create New Empty Node] 5. [Initialize Temporary Pointer]
NEW NODE SAVE FIRST
2. [Copy information content into new 6. [Search for Predecessor of new node]
node] Repeat while SAVE ≠ LAST &
INFO(NEW) X INFO(NEW) ≥ INFO(LINK(SAVE))
3. [Is Linked List Empty?] SAVELINK(SAVE)
IF FIRST = NULL 7. [Set link field of NEW node and its
THEN LINK(NEW) NEW Predecessor]
FIRST LAST NEW LINK(NEW) LINK(SAVE)
Return LINK(SAVE) NEW
4. [Does new node precedes all other IF SAVE = LAST
nodes in List?] THEN LAST NEW
IF INFO(NEW)≤ INFO(FIRST) 8. [Finished]
THEN LINK(NEW) FIRST Return
LINK(LAST) NEW
FIRST NEW
Return
Procedure: CIR_INS_ORD(3,FIRST,LAST)
1. [Create New Empty Node] 4. [Does new node precedes all other
NEW NODE nodes in List?]
2. [Copy information content into new IF INFO(NEW)≤ INFO(FIRST)
node] THEN LINK(NEW) FIRST
INFO(NEW) X LINK(LAST) NEW
3. [Is Linked List Empty?] FIRST NEW
IF FIRST = NULL Return
THEN LINK(NEW) NEW
FIRST LAST NEW
Return FIRST
NEW
FIRST LAST 3
LAST
3
5 10 15 20
NEW
FIRST
Procedure: CIR_INS_ORD(3,FIRST,LAST)
1. [Create New Empty Node] 4. [Does new node precedes all other
NEW NODE nodes in List?]
2. [Copy information content into new IF INFO(NEW)≤ INFO(FIRST)
node] THEN LINK(NEW) FIRST
INFO(NEW) X LINK(LAST) NEW
3. [Is Linked List Empty?] FIRST NEW
IF FIRST = NULL Return
THEN LINK(NEW) NEW
FIRST LAST NEW
Return FIRST
NEW
FIRST LAST 3
LAST
3
5 10 15 20
NEW
FIRST
Procedure: CIR_INS_ORD(18,FIRST,LAST)
5. [Initialize Temporary Pointer] 7. [Set link field of NEW node and its
SAVE FIRST Predecessor]
6. [Search for Predecessor of new node] LINK(NEW) LINK(SAVE)
Repeat while SAVE ≠ LAST & LINK(SAVE) NEW
INFO(NEW) ≥ INFO(LINK(SAVE)) IF SAVE = LAST
SAVELINK(SAVE) THEN LAST NEW
8. [Finished]
NEW Return
18
LAST
SAVE
5 10 15 20
FIRST
Procedure: CIR_INS_ORD(18,FIRST,LAST)
5. [Initialize Temporary Pointer] 7. [Set link field of NEW node and its
SAVE FIRST Predecessor]
6. [Search for Predecessor of new node] LINK(NEW) LINK(SAVE)
Repeat while SAVE ≠ LAST & LINK(SAVE) NEW
INFO(NEW) ≥ INFO(LINK(SAVE)) IF SAVE = LAST
SAVELINK(SAVE) THEN LAST NEW
8. [Finished]
NEW Return
18
LAST
SAVE
5 10 15 20
FIRST
Procedure: CIR_DELETE(X,FIRST,LAST)
This algorithm delete a node whose address is given by variable X.
FIRST & LAST are pointers to the First & Last elements of a Circular linked list, respectively.
Typical node contains INFO and LINK fields.
SAVE & PRED are temporary pointer variable.
Procedure: CIR_DELETE(X,FIRST,LAST)
1. [Is Empty List?] 6. [End of Linked List?]
IF FIRST = NULL IF SAVE ≠ X
THEN write(‘Linked List is THEN write(‘Node not found’)
Empty’) Return
Return 7. [Delete X]
2. [Initialize Search for X] IF X = FIRST
SAVE FIRST THEN FIRSTLINK(FIRST)
3. [Find X] LINK(LAST)FIRST
Repeat thru step 5 ELSE LINK(PRED)LINK(X)
while SAVE≠X & SAVE≠LAST IF X = LAST
4. [Update predecessor marker] THEN LAST PRED
PRED SAVE 8. [Free Deleted Node]
5. [Move to next node] Free (X)
SAVE LINK(SAVE)
Procedure: CIR_DELETE(7541,FIRST,LAST)
1. [Is Empty List?] 6. [End of Linked List?]
IF FIRST = NULL IF SAVE ≠ X
THEN write(‘Linked List is Empty’) THEN write(‘Node not found’)
Return Return
2. [Initialize Search for X] 7. [Delete X]
SAVE FIRST IF X = FIRST
3. [Find X] THEN FIRSTLINK(FIRST)
Repeat thru step5 while SAVE≠X & SAVE≠LAST LINK(LAST)FIRST
4. [Update predecessor marker] ELSE LINK(PRED)LINK(X)
PRED SAVE IF X = LAST
5. [Move to next node] THEN LAST PRED
SAVE LINK(SAVE) 8. [Free Deleted Node]
Free (X)
SAVE
PRED
5 10 15 20 25 30
4455 8564 7541 1254 3254
5000
FIRST LAST
Procedure: CIR_DELETE(7541,FIRST,LAST)
1. [Is Empty List?] 6. [End of Linked List?]
IF FIRST = NULL IF SAVE ≠ X
THEN write(‘Linked List is Empty’) THEN write(‘Node not found’)
Return Return
2. [Initialize Search for X] 7. [Delete X]
SAVE FIRST IF X = FIRST
3. [Find X] THEN FIRSTLINK(FIRST)
Repeat thru step5 while SAVE≠X & SAVE≠LAST LINK(LAST)FIRST
4. [Update predecessor marker] ELSE LINK(PRED)LINK(X)
PRED SAVE IF X = LAST
5. [Move to next node] THEN LAST PRED
SAVE LINK(SAVE) 8. [Free Deleted Node]
Free (X)
PRED
5 10 15 25 30
4455 8564 1254 3254
5000
FIRST LAST
Circularly Linked List with Header Node
We can have special node, often referred to as Head node of Circular Linked List.
Head node does not have any value.
Head node is always pointing to the first node if any of the linked list.
One advantage of this technique is Linked list is never be empty.
Pointer variable HEAD contains the address of head node.
HEAD
10 15 20 25 30
HEAD
Empty List
LINK(HEAD) HEAD
Doubly Linked Linear List
Typical node of doubly linked linear list contains INFO, LPTR RPTR Fields
LPTR is pointer variable pointing to Predecessor of a node
RPTR is pointer variable pointing to Successor of a node
Left most node of doubly linked linear list is called L, LPTR of node L is always NULL
Right most node of doubly linked linear list is called R, RPTR of node R is always NULL
Typical node of
Doubly Linked List L Doubly linked linear list R
Insert node in Doubly Linked List
Insertion in the middle of Doubly Linked Linear List
Before Insertion M
L R
LPTR(NEW) LPTR(M)
NEW RPTR(NEW) M
LPTR(M) NEW
RPTR(LPTR(NEW)) NEW
After Insertion
M
L R
NEW
Insert node in Doubly Linked List
Left most insertion in Doubly Linked Linear List
Before Insertion
M
L R
LPTR(NEW) NULL
RPTR(NEW) M
NEW LPTR(M) NEW
L NEW
M After Insertion
L
L R
NEW
Procedure: DOU_INS (L,R,M,X)
This algorithm inserts a new node in doubly linked linear list.
The insertion is to be performed to the left of a specific node with its address given by the
pointer variable M.
Typical node of doubly linked list contains following fields LPTR, RPTR and INFO.
LPTR is pointer variable pointing to Predecessor of a node.
RPTR is pointer variable pointing to Successor of a node.
L & R are pointer variables pointing for Leftmost and Rightmost node of Linked List.
NEW is the address of New Node.
X is value to be inserted.
Procedure: DOU_INS (L,R,M,X)
1. [Create New Empty Node] 4. [Is left most insertion ?]
NEW NODE IF M = L
2. [Copy information field] THEN LPTR(NEW) NULL
INFO(NEW) X RPTR(NEW) M
3. [Insert into an empty list] LPTR(M) NEW
IF R = NULL L NEW
THEN LPTR(NEW) NULL Return
RPTR(NEW) NULL 5. [Insert in middle]
L R NEW LPTR(NEW) LPTR(M)
Return RPTR(NEW) M
LPTR(M) NEW
RPTR(LPTR(NEW)) NEW
Return
PROCEDURE: DOU _DEL (L, R, OLD)
This algorithm deletes the node whose address is contained in the variable OLD.
Typical node of doubly linked list contains following fields LPTR, RPTR and INFO.
LPTR is pointer variable pointing to Predecessor of a node.
RPTR is pointer variable pointing to Successor of a node.
L & R are pointer variables pointing for Leftmost and Rightmost node of Linked List.
Delete from Doubly Linked List
10 L R NULL
OLD
L R
L L R R
10 L R NULL
OLD
L R
L R
2+2*2+2*2
1 2
3
4
A repeated scanning from left to right is needed as operators appears inside the operands.
Repeated scanning is avoided if the infix expression is first converted to an equivalent
parenthesis free prefix or suffix (postfix) expression.
Prefix Expression: Operator, Operand, Operand
Postfix Expression: Operand, Operand, Operator
Difference
Sr. Infix Postfix Prefix
1 a a a
2 a+b ab+ +ab
3 a+b+c ab+c+ ++abc
4 a + (b + c) abc++ +a+bc
5 a + (b * c) abc*+ +a * b c
6 a * (b + c) abc+* *a+bc
7 a*b*c a b *c* ** a b c
(a * (b + c))
Infix to Postfix Conversion
Convert infix: A+B×(C−D) Step Action Stack Output
Deletion Insertion
Front Rear
Applications of Queue
Queue of people at any service point such as ticketing etc.
Queue of air planes waiting for landing instructions.
Queue of processes in OS.
Queue is also used by Operating systems for Job Scheduling.
When a resource is shared among multiple consumers. E.g., in case of printers the first one to
be entered is the first to be processed.
When data is transferred asynchronously (data not necessarily received at same rate as sent)
between two processes. Examples include IO Buffers, pipes, file IO, etc.
Queue is used in BFS (Breadth First Search) algorithm. It helps in traversing a tree or graph.
Queue is used in networking to handle congestion.
Procedure: Enqueue (Q, F, R, N,Y)
This procedure inserts Y at rear end of Queue. R
FR F R F R
FR F R F R
Insert ‘B’ R=3 Delete ‘B’ (R=4) >= (N=4) (Size of Queue)
R=2 F=3 Queue Overflow
F=1 A B B C
Queue Overflow, but space is
there with Queue, this leads to
FR F R the memory wastage
Circular Queue
A more suitable method of representing simple queue which prevents an excessive use of
memory is to arrange the elements Q[1], Q[2]….,Q[n] in a circular fashion with Q[1] following
Q[n], this is called circular queue.
In circular queue the last node is connected back to the first node to make a circle.
Circular queue is a linear data structure. It follows FIFO principle.
It is also called as “Ring buffer”.
Circular Queue.
6
Queue is represented by a vector Q containing N elements.
F is pointer to the front element of a queue. R F
FR F R F R
FR F R F R
FR F R
Priority Queue
A queue in which we are able to insert & remove items from any position based on some
property (such as priority of the task to be processed) is often referred as priority queue.
Below fig. represent a priority queue of jobs waiting to use a computer.
Priorities are attached with each Job
Priority 1 indicates Real Time Job
Priority 2 indicates Online Job
Priority 3 indicates Batch Processing Job
Therefore if a job is initiated with priority i, it is inserted immediately at the end of list of other
jobs with priorities i.
Here jobs are always removed from the front of queue.
Priority Queue
An extension of queue.
Each element is has priority associated with it, and get served based on the priority.
Priority Queue
Element Priority
Ascending Priority Queue
A 7
Descending Priority Queue
B 6
C 4 E D C B F A
D 2
E 1
F 6 A B F C D E
Priority Queue Cont…
Task R1 R2 … Ri-1 O1 O2 … Oj-1 B1 B2 … Bk-1 …
Priority 1 1 … 1 2 2 … 2 3 3 … 3 …
Ri Oj Bk
Priority Queue viewed as a single queue with insertion allowed at any position
Priority - 1 R1 R2 … Ri-1 Ri
Priority - 2 O1 O2 … Oj-1 Oj
Priority - 3 B1 B2 … Bk-1 Bk
Insertion Order Strict FIFO. FIFO with cyclic behavior. Based on assigned priority.
When order of arrival is most When cyclic and memory When priority supersedes
Best Use Case
important. efficiency is needed. order of arrival.
THANK YOU
chapter-1 is finished
Basic Analysis: Differences among best, expected, and worst case behaviors of an
algorithm, Asymptotic analysis, Big O notation: formal definition and use, big omega and
big theta notation, Time and space trade-offs in algorithms, Recurrence relations, Analysis
of iterative and recursive algorithms.