Unit 2: Linear Data Structures
Lecturer: Shimirwa Aline Valerie
Content
UNIT 1(Introduction To Algorithms And Data Structures)
Algorithms: Definition, Properties, Performance Analysis, Space Complexity, Time Complexity,
Asymptotic Notations. Data structures: Introduction, Data Structures types, DS Operations.
UNIT 2(Linear Data Structures)
Arrays, Stacks: Introduction, Stack Operations, Applications: Infix to Postfix Conversion, Evaluation
of Postfix Expression. Queues: Introduction, Operations on queues, Circular queues, Priority queues.
Linked lists: Introduction, Singly linked lists, Circular linked lists, Doubly linked lists, Applications.
Implementation of Stack and Queue using linked list.
UNIT 3(Non-linear Data Structure)
Trees: Basic terminology, Binary Trees, Binary Tree Representation, Graphs: Terminology, Sequential
and linked Representations of graphs, Graph Traversal : Depth First Search and Breadth First Search,
Spanning Trees, Spanning Trees: Prims and Kruskal algorithm
Content
UNIT 4(Sorting and Searching Algorithm)
Sorting: Introduction, Selection sort, Bubble sort, Insertion sort, Merge sort, Quick sort, Heap Sort.
Searching: Introduction, Linear search, Binary search, Hash table methods, Hashing Functions.
Types of the array
Arrays Arrays are classified as follows:
Array: is a container which can store more than one 1. Single Dimensional Arrays / One Dimensional
elements and these elements should be of the same Arrays(1-D array).
data type.
2. Multi-Dimensional array(Two Dimensional
Element: Each item stored in an array is called an Array, Three Dimensional Array)
element.
Index: Each location of an element in an array has a
numerical index, which is used to identify the
element.
The elements are stored from left to right with the
left-most index being the 0th index and the rightmost
index being the (n-1) index.
Initialization of Single Dimensional Array
We use the following general syntax for
One Dimensional Array(1-D Array) declaring and initializing a single dimensional
array with size and initial values.
One dimensional arrays: are used to store list of
values of same datatype. They involve single sub-
scripting.
Example Code:
Declaration of One Dimensional Array
We use the following general syntax for declaring a The array must be initialized if it is created
single dimensional array: without specifying any size. In this case, the size
of the array is decided based on the number of
values initialized.
Example code :
The above declaration of single dimensional array
holds 10 elements in continuous memory locations Example Code:
of 4 bytes each with the name a and tells the
compiler to allow only integer values into those
memory locations.
Memory Representation Of A One Let’s declare an array of five integers like this:
Dimensional Array(1-d Array)
Let's assume that the first element of the array has
The diagram below is one typical way to represent the
the address 1200. This means that &a[0] would be
memory used by an array
1200. Since an int occupies 4 bytes, the address of
the second element of the array, &a[1] would be
1204, the address of the third element of the array,
&a[2] would be 1208, and so on.
General Formula:
address of a[i] = Base address + (i* size of the datatype)
Advantages And Disadvantages Of An Disadvantages of the array
Array In an array, it is essential to identify the number of
elements to be stored.
Advantages of the array It is a static structure. It means that in an array, the
memory size is fixed.
Arrays can represent multiple data items of the same
type using a single name. When it comes to insertion and deletion, it is a bit
difficult because the elements are stored
It enables us to collect the number of elements in it. sequentially and the shifting operation is
Arrays have a safer cache positioning that improves expensive.
performance.
Insertion at the Beginning of an Array
When the insertion happens at the beginning, it
Basic Operations On The Array causes all the existing data items to shift one step on
the right.
Following are the basic operations supported by an Algorithm for inserting an element at the beginning:
array: Let’s assume a is an array with n elements. The
Traverse: Prints all the array elements one by one. maximum numbers of elements it can store is defined
by MAX.
Insertion : Adds an element in the array. We check if an array has any empty space to store
any element and then we proceed with the insertion
Deletion : Deletes an element at the given index. process.
Search: Searches an element using the given index Begin
IF N = MAX, return ELSE
Update: Updates an element at the given index.
For All Elements in A
Insertion Operation Move to next adjacent location
Insert operation is to insert elements into an array. A[FIRST] = New_Element
A new element can be added at the beginning, end, N=N+1
or any given position of array. end
Time complexity = O(n)
Implementation in C
Insertion Operation on the array
Insertion at the Beginning of an Array
When the insertion happens at the beginning, it causes all
the existing data items to shift one step on the right.
Algorithm for inserting an element at the beginning:
We assume A is an array with N elements. The
maximum numbers of elements it can store is defined
by MAX.
We check if an array has any empty space to store any
element and then we proceed with the insertion process.
Begin
IF N = MAX, return
ELSE
For All Elements in A
Move to next adjacent location
A[FIRST] = New_Element
N = N + 1
end
Implementation in C
Insertion Operation on the array
Insertion at the Given Index of an Array
we are given the exact location ( index) of an array where
a new data element (value) needs to be inserted.
First we shall check if the array is full, if it is not, then we
shall move all data elements from that location one step
on the right to make a room for a new element.
Algorithm for inserting an element at the given index
Let’s assume a is an array with n elements. The
maximum numbers of elements it can store is defined by
MAX.
begin
IF N = MAX, return ELSE
N=N+1
SEEK Location index
For All Elements from A[index] to A[N] Move to next
adjacent location
A[index] = New_Element end
Time Complexity = O(n)
Implementation in C
Insertion Operation on the array
Insertion After the Given Index of an Array
Algorithm for inserting an element After the given
index:
We assume A is an array with N elements. The maximum
numbers of elements it can store is defined by MAX.
begin
IF N = MAX, return ELSE
SEEK Location index
For All Elements from A[index + 1] to A[N] Move
to next adjacent location
A[index + 1] = New
N=N+1
Time Complexity = O(n)
Implementation in C
Insertion Operation on the array
Insertion Before the Given Index of an Array
Algorithm for inserting an element After the given
index:
We assume A is an array with N elements. The Do It as an Exercise
maximum numbers of elements it can store is defined
by MAX.
begin
IF N = MAX, return ELSE
N=N+1
SEEK Location index
For All Elements from A[index - 1] to A[N] Move
to next adjacent location
A[index - 1] = New_Element end
Time Complexity = O(n)
Implementation in C
Delete Operation On The Array
Deletion: refers to removing an existing element from
the array and re-organizing all elements of an array.
Algorithm for deleting an element from an array:
Consider LA is a linear array with N elements and K is
a positive integer. Following is the algorithm to delete
an element available at the Kth position of LA.
1. Start
2. Set I=K
3. Repeat steps 4 and 5 while J < N
4. Set LA[I] = LA[I+1]
5. Set I = I+1
6. Set N = N-1
7. Stop
Time Complexity = O(n)
Implementation in C
Search Operation On The Array
You can perform a search for an array element based on
its value or its index.
Algorithm for searching an element in an array
Consider LA is a linear array with N elements. Following is
the algorithm to find an element with a value of ITEM
using sequential search:
1. Start
2. Set item, N, i
3. Repeat steps 4 and 5 while J < N
4. IF LA[i] is equal ITEM THEN GO TO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop
Time Complexity = O(n)
Update Operation In An Array Implementation in C
Update operation refers to updating an existing element
in the array at a given index.
Algorithm for updating an element in an array
Consider LA is a linear array with N elements. Following is
the algorithm to update an element available at the K th
position of LA.
1. Start
2. Set index, n, Item
3. Set LA[K] = ITEM
4. Stop
Pointers and Arrays vowels + i. Moreover, pvowels + i and vowels + i
returns the same thing (address of the i th element of the
array vowels). On the other hand, *(pvowels + i) and
*(vowels + i) both return the ith element of the array
Pointers: are special variables which are used to
vowels. Why is that so?
store the address of the other variables.
Array its self is a pointer because once its created, This is because the name of an array itself is a
it points to the address of the first element. (constant) pointer to the first element of the array. In
For example, in the following code, the pointer other words, the notations vowels, &vowels[0], and
vowels + 0 all point to the same location.
variable pc stores the address of the character
variable c.
In the above code , c is a scalar variable that can
store only a single value. However, you are
already familiar with arrays that can hold multiple
values of the same data type in a contiguously
allocated memory block. So, you might wonder,
can we have pointers to arrays too? Indeed, we
can.
Moreover, unused memory can be freed as soon as
it is no longer required by invoking the free()
Dynamic Memory Allocation for Arrays function. On the down side, with dynamic memory
allocation, one must responsibly call free()
wherever relevant. Otherwise, memory leaks would
occur.
We can dynamically allocate (contiguous) memory
using blocks pointers.
In the code, we allocated five contiguous bytes of
memory to store five characters.
Subsequently, we used array notations to traverse
the blocks of memory as if pvowels is an array.
However, remember that pvowels actually is a
pointer. Pointers and arrays, in general, are not the
same thing.
So why is this useful to dynamically allocate
memory? The reason is that, while declaring an
array, the number of elements that it would contain
must be known beforehand. However, by using
dynamic memory allocation, one can allocate just
as much memory as required by a program.
Initialization of Single Dimensional Array
We use the following general syntax for
Two Dimensional Array(2-D Array) declaring and initializing a two dimensional
array with size and initial values.
Two dimensional arrays: is the array of arrays is c.
In simple words, an array created with more than
one dimension (size) is called as multi dimensional
array. Multi dimensional array can be of two Example Code:
dimensional array or three dimensional
array or four dimensional array or more...
How Elements are represented in the memory?
Declaration of One Dimensional Array
Below is the example for the pictorial representation of
We use the following general syntax for declaring a elements and their address for array a.
two dimensional array:
Example code :
General Formula to calculate the address:
address of a[i][j] = Base address + [(i*#columns) +j]*size
Implementation in C
Inserting Elements in 2-D Arrays
For inserting elements in 2-D Arrays, we need to insert
the data in both rows and columns.
In the above process for initializing the data in an array,
we had predefined the values(Compiler time
initialization).
Here, let’s initialize elements by asking the user to insert
the elements.
Implementation in C
Update Elements in 2-D Arrays
We can update the elements of 2D array either by
specifying the element to be replaced or by
specifying the position where replacement has to be
done.
For updating the array we require:
•Elements of an array
•Element or position, where it has to be inserted
•The value to be inserted
Why Linked List?
Arrays can be used to store linear data of similar
Linked List types, but arrays have the following limitations:
Linked List is a linear data structure where elements
are not stored at a contiguous location. the elements The size of the arrays is fixed: So we must know
are linked using pointers. In other words, Linked List the upper limit on the number of elements in
is a collection of connected nodes where by each advance.
node stores the data and the address of the next node. Insertion of a new element / Deletion of a existing
element in an array of elements is expensive: The
room has to be created for the new elements and to
create room existing elements have to be shifted
but in Linked list if we have the head node then we
can traverse to any node through it and insert new
node at the required position.
Major differences between array and linked-list
ARRAY LINKED LIST
Elements in the array are stored in contiguous Elements in the linked list are not stored in
location contiguous location
Fixed in size Dynamic in size
Uses less memory than linked list Uses more memory because it stores both data and
the address of the next node
Elements in the array can be accessed easily Elements in the linked list can be accessed by
traversing the whole linked list
Insertion and deletion operations take time Insertion and deletion operations are faster
Linked List Basic LinkedList Operations
Types of Linked Lists Basic LinkedList operations are :
Simple Linked List: In this type of linked list, one Insertion: Adds an element at the beginning of
can move or traverse the linked list in only one the list.
direction. where the next pointer of each node points Deletion: Deletes an element at the from the
to other nodes but the next pointer of the last node linked list.
points to NULL. It is also called “Singly Linked Display: Displays the complete list.
List”. Search: Searches an element in the linked list.
Doubly Linked List: In this type of linked list,
where by one can move or traverse the linked list in
both directions (Forward and Backward)
Circular Linked List: In this type of linked list, the
last node of the linked list contains the link of the
first/head node of the linked list in its next pointer.
6. If there is no memory to allocate for head
Creation of Singly Linked Lists node(i.e head==NULL). Then print some error
message and terminate program, otherwise move
Step by step descriptive logic to create a linked list to below step.
1.The first step of creating linked list of n nodes starts 7. Input data from user and assign to head
from defining node structure
8. At first head node points to NULL Hence:
9. Now, we are done with head node we should
move to creation of other nodes. Copy reference
2. Declare a pointer to store a link of the first node in of head to some other temporary variable(i.e to
the linked list store reference of previous node).
3. Input number of nodes to create from user, store it
in some variable 10. Allocate memory and assign memory
4. Declare two more helper variable of node type reference to newNode.
5.If then, create head node. use dynamic memory 11. If memory got allocated successfully then
allocation to allocate memory for a node read data from user and assign to data section of
new node.
How to traverse a linked list?
Creation of Singly Linked Lists(cont..) 1. Create a temporary variable for traversing.
Assign reference of head node to it.
Step by step descriptive logic to create a linked list
12. Make sure new node points to NULL.
2. Repeat below step till
13. Now link previous node with newly created node:
3. Print current node.
14. Make current node as previous node using:
4. Once done, move to next node using
5. Go back to 2nd step.
15. Repeat step 10-14 for remaining n-2 nodes.
Creation of Singly Linked Lists(cont..)
C code for creating singly linked list and how to
display the elements.
Insertion in Linked List
One of the most primitive operations that can be done in a singly linked list is the insertion of a
node. Memory is to be allocated for the new node before reading the data. The new node will
contain empty data field and empty next field. The data field of the new node is then stored with
the information read from the user. The next field of the new node is assigned to NULL. Then a
new node can be added in three ways :
At the beginning of the linked list
After a given node.
At the end of the linked list.
Insertion in Linked List ( Insert a node at
the beginning)
Algorithm to insert node at the beginning of singly
linked list
1. Create a new node, say newNode.
2. Link the newly created node with the head
node( i.e. the newNode will now point
to head node).
3. Make the new node as the head node(i.e.
now head node will point to newNode).
Insertion in Linked List ( Insert a node at
the beginning)
Pseudocode
Complexity Analysis of inserting a node at the beginning
of the linked list:
We have a pointer to the head and we can
directly attach a node and change the pointer.
So the Time complexity of inserting a node at
the head position is O(1) as it does a constant
amount of work.
Insertion in Linked List (Insert a node at
any position )
Algorithm to insert node at any position of singly
linked list
1. Create a new node
2. Traverse to the n-1th position of the linked list and
connect the new node with the n+1th node. Means
the new node should also point to the same node
that the n-1th node is pointing to. (newNode->next
= temp->next where temp is the n-1th node).
3. Now at last connect the n-1th node with the new
node i.e. the n-1th node will now point to new node.
(temp->next = newNode where temp is the n-
1th node).
Insertion in Linked List (Insert a node after
a given node )
Pseudocode
Time complexity of inserting a node in the middle of
the linked list is O(n).
Insertion in Linked List (Insert a node at the
end)
Algorithm to insert node at the end of singly linked
list
1. Create a new node and make sure that the address
part of the new node points
to NULL i.e. newNode->next=NULL.
2. Traverse to the last node of the linked list and
connect the last node of the list with the new node,
i.e. last node will now point to new node.
(lastNode->next = newNode).
Insertion in Linked List (Insert a node at the
end)
Pseudocode
Time complexity: Since there is a loop from head to
end, the function does (n) work. Thus time complexity
of adding a node a the end is O(n).
Deletion from Linked List
When deleting a node from the linked list, memory is to be released for the node to be deleted. A
node can be deleted in three different position:
At the beginning of the linked list
After a given node.
At the end of the linked list.
Deletion from Linked List(delete node at the
beginning )
Algorithm to delete node at the beginning of singly
linked list
1. Copy the address of first node (i.e. head node to
some temp variable say toDelete).
2. Move the head to the second node of the linked list
i.e. head = head->next.
3. Disconnect the connection of first node to second
node.
4. Free the memory occupied by the first node.
Deletion from Linked List(delete node at the
beginning )
pseudocode for deleting first node in Singly linked
list
Complexity Analysis of deleting a node at the
beginning of the linked list:
We have a pointer to the head and we can
directly attach a node and change the pointer.
So the Time complexity of deleting the first
node is O(1) as it does a constant amount of
work.
Deletion from Linked List (delete a node at
the End )
Algorithm to delete node at the end of singly linked
list
1. Traverse to the last node of the linked list keeping
track of the second last node in some temp variable
say secondLastNode.
2. If the last node is the head node then make the head
node as NULL else disconnect the second last node
with the last node( i.e. secondLastNode->next =
NULL).
3. Free the memory occupied by the last node.
Deletion from Linked List (delete a node at
the End )
Pseudocode for deleting last node in Singly linked
list
Time complexity: Since there is a loop from head to
end, the function does (n) work. Thus time complexity
of deleting a node a the end is O(n).
Deletion from Linked List(delete a node from
the a specific position )
Algorithm to delete node from the middle of singly
linked list
1. Traverse to the nth node of the singly linked list and
also keep reference of n-1th node in some temp
variable say prevnode.
2. Reconnect the n-1th node with
the n+1th node(i.e. prevNode->next = toDelete-
>next)
3. Free the memory occupied by the nth node
i.e. toDelete node.
Deletion from Linked List(delete a node from
the middle )
Pseudocode for deleting a node in the middle of a
Singly linked list
Time complexity of deleting a node in the middle of
the linked list is O(n).
Find Length of the Linked List
pseudocode for counting number of nodes in Singly
Linked List Exercise: write a C program to count nodes in
a Singly Linked List.
5. Point the previous node to current node and current
Reverse a Singly Linked List node to head node. Means they should now point
to prevNode =curNode; and curNode = head.
Steps to reverse a Singly Linked List
6. Repeat steps 3-5 till head pointer becomes NULL.
1. create two more pointers other 7. Now, after all nodes has been re-connected in the
than head namely prevNode and curNode that will hold the reverse order. Make the last node as the first node.
reference of previous node and current node respectively. Make Means the head pointer should point
to prevNode pointer. Perform head = prevNode;.
sure that prevNode points to first node i.e. prevNode = head. Finally you end up with a reversed linked list of its
head should now point to its next node i.e. the second node head original.
= head->next. curNode should also points to the second node
i.e. curNode = head.
2. Now, disconnect the previous node i.e. the first node from
others. We will make sure that it points to none. As this node is
going to be our last node. Perform operation prevNode->next =
NULL.
3. Move head node to its next node i.e. head = head->next
4. Now, re-connect the current node to its previous node
i.e. curNode->next = prevNode;
Reverse a Singly Linked List
Pseudocode
Doubly Linked List Representation of basic structure of a doubly
linked list in C language
Doubly linked list: is a collection of nodes linked together
in a sequential way. Doubly linked list is almost similar to
singly linked list except it contains two address fields, where
one of the address field contains reference of the next node
and other contains reference of the previous node.
First and last node of a linked list points to a NULL value.
Doubly linked list is sometimes also referred as bi-
directional linked list since it allows traversal of nodes in
both direction. The basic structure of a doubly linked list is
represented as:
Advantages and Disadvantages
of Doubly linked list Disadvantages:
It uses extra memory when compared to array
Advantages: and singly linked list.
Doubly Linked List Allows traversal of nodes in both
Since elements in memory are stored randomly,
direction which is not possible in singly linked list.
hence elements are accessed sequentially no
Deletion of nodes is easy when compared to Singly direct access is allowed.
linked list, as in singly linked list deletion requires a
pointer to the node and previous node to be deleted.
Which is not in case of doubly linked list we only need
the pointer which is to be deleted.
Reversing the list is simple and straightforward.
Can allocate or de-allocate memory easily when
required during its execution.
It is one of most efficient data structure to implement
when traversing in both direction is required.
Applications/Uses of doubly linked list in
real life
There are various application of doubly linked list in the real world. Some of them can be
listed as:
Doubly linked list can be used in navigation systems where both front and back navigation is
required.
It is used by browsers to implement backward and forward navigation of visited web pages
i.e. back and forward button.
It is also used by various application to implement Undo and Redo functionality.
It can also be used to represent deck of cards in games.
It is also used to represent various states of a game.
Create Doubly Linked List
Steps to create Doubly linked list
1. Create a head node and assign some data to its data field.
2. Make sure that the previous and next address field of
the head node must point to NULL.
3. Make the head node as last node.
4. Create a new node and assign some data to its data field.
5. Make sure that the next address field of new node must point
to NULL.
6. Link the new node previous address field with lastNode.
7. Link the lastNode next address field with newNode.
8. Move the lastNode to newNode i.e. last node will now point
to new node.
9. Repeat Steps 4-8 if you want to add more nodes to the list .
Create Doubly Linked List
Pseudocode for create a Doubly linked list
Traverse Or Display Doubly Linked
List pseudocode for traverse or display Doubly
linked list from End
pseudocode for traversing or displaying Doubly linked
list from beginning
Insertion in Doubly linked List(Inserting
Node At The Beginning )
Algorithm for Inserting Node At The Beginning Of A
Doubly Linked List
1. Create a new node
allocate memory for newNode
assign the data to newNode
2. Set prev and next pointers of new node
Point next of NewNode to the first node of the
doubly linked list
point preview to null
3. Make newNode as head node.
Point prev of the first node to NewNode (now the
previous Head is the second node)
Point Head to NewNode
Insertion in Doubly linked List(Inserting
Node At The Beginning )
Pseudocode for Inserting Node At The Beginning Of A
Doubly Linked List
Exercise: write a C program to insert a new
node at the beginning of a Doubly Linked List.
Insertion in Doubly linked List(Inserting
Node At The End )
Algorithm for Inserting Node At The End Of A
Doubly Linked List
1. Create a newNode
2. Set prev and next pointers of newNode and the
prevNode
If the linked list is empty, make the newNode as
the head node. Otherwise, traverse to the end of
the doubly linked list
Insertion in Doubly linked List(Inserting
Node At The End )
Pseudocode for Inserting Node At The End Of A
Doubly Linked List
Exercise: write a C program to insert a new
node at the End of a Doubly Linked List.
Insertion in Doubly linked List(Inserting
Node At Any Position)
Algorithm for Inserting Node At Any Position Of A
Doubly Linked List
1. Traverse to N-1 node in the list. Where N is the position
to insert. Say temp now points to N-1th node.
2. Create a newNode that is to be inserted and assign some
data to its data field.
3. Connect the next address field of newNode with the
node pointed by next address field of temp node.
4. Connect the previous address field of newNode with
the temp node.
5. Check if temp->next is not NULL then, connect the
previous address field of node pointed
by temp.next to newNode.
6. Connect the next address field of temp node
to newNode i.e. temp->next will now point to newNode.
Insertion in Doubly linked List(Inserting
Node At Any Position)
Pseudocode for Inserting Node At Any Position Of A
Doubly Linked List
Deletion in Doubly linked List(Deleting
Node At The Beginning ) Exercise: write a C program to delete a new
node at the beginning of a Doubly Linked List.
Pseudocode for Deleting Node At The Beginning Of A
Doubly Linked List
Deletion in Doubly linked List(Deleting
Node At The End ) Exercise: write a C program to delete a node
at the end of a Doubly Linked List.
Pseudocode for Deleting Node At The End Of A
Doubly Linked List
Deletion in Doubly linked List(Deleting
Node At Any Position) Exercise: write a C program to delete a node
at any position of a Doubly Linked List.
Pseudocode for Deleting Node At Any Position Of A
Doubly Linked List
Reverse a Doubly Linked List
Pseudocode
Exercise: Write a C program to create a doubly
linked list and reverse the linked list.