CPU 1142 DATA STRUCTURES AND ALGORITHMS Day School 1 M. K. A. Ariyaratne B [email protected]T 0112 881225 Department of Mathematics and Computer Science Faculty of Natural Sciences The Open University of Sri Lanka Sri Lanka July 08, 2014 M. K. A. Ariyaratne Day School 1 July 08, 2014 1 / 74
74
Embed
CPU 1142 DATA STRUCTURES AND ALGORITHMSData Structures and Algorithms - Overview Data Structures - Overview Data Structures implement ADTs. Data structures help in e cient storing
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Let’s start learning basics you need in C language, for this course.
C is a general purpose programming language.
Fundamental Data types: character, integer, float, double
C programs are not limited to a linear sequence of statements.
During its process, a program may repeat segments of code, or
take decisions and separate. For this C has several flow control
operators
if if -else switch
while do - while for
M. K. A. Ariyaratne Day School 1 July 08, 2014 28 / 74
Preliminaries - C Language
C Language (2)
We can write functions in C.
These functions may return a value or may not return a value.
Basic structure of a C program is:
#include <stdio.h>
#include <stdlib.h>
int main( )
{printf(”Hello world !”);
return 0;
}stdio.h is the header file corresponding for input and output.
main function is the heart of any C program, because the
execution starts there.M. K. A. Ariyaratne Day School 1 July 08, 2014 29 / 74
Preliminaries - C Language
Functions in a C Program
As you know there are two types of functions in C.
Library Functions (ex: printf())
User Defined Functions
A function is a block of statements written to do a specific task.
It has a name, inputs it needs to complete the task (we call them
arguments), outputs it gives after completing the task.
In C, A function’s name is unique and is global.
Using functions in a program will organize the program and
reduce the length of the program.
You can execute a same function many times, as needed.
M. K. A. Ariyaratne Day School 1 July 08, 2014 30 / 74
Preliminaries - C Language
Structure of a Function
There are two parts of a Function: function header and functionbodyFunction header: ReturnType FunctionName (ArgumentList )
Function body: Whatever in between { }int sum(int x, int y){
int ans = 0;ans = x + y;return ans;
}Calling to a function can be made from main( ) function or fromanother function.
int main( ){
int myAns;myAns = sum (2, 3)return 0;
}M. K. A. Ariyaratne Day School 1 July 08, 2014 31 / 74
Preliminaries - C Language
Programming in C
We proceed to the rest of the chapters hoping that you have used
following C operators before and you know how they work.
1 if
2 if - else
3 switch
4 for loop
5 while loop
6 do - while loop
7 Early loop exit: break statement
8 continue statement
9 pointers
M. K. A. Ariyaratne Day School 1 July 08, 2014 32 / 74
Lists
LESSON 03
Lists
M. K. A. Ariyaratne Day School 1 July 08, 2014 33 / 74
Lists
Lists - Introduction
List is an Abstract Data Type.
That is a list is a data holding method defined by some one. It has
its own operators.
But implementation of a List can be done in many ways.
A list refers to a collection of data items. (e.g.: Think of your
mother’s marketing / shopping list)
EggsTomatoesButterApplesOrangesBread
M. K. A. Ariyaratne Day School 1 July 08, 2014 34 / 74
Lists
Lists - Introduction(2)
It is necessary to add or delete items from a list.
EggsTomatoesButterApplesOrangesBreadChickenMilk
List is a flexible ADT. They can grow or shrink on demand.
You can access, insert or delete any element of a list.
Also you can concatenate two lists or split a list into sub lists.
M. K. A. Ariyaratne Day School 1 July 08, 2014 35 / 74
Lists
Lists - Introduction(3)
Mathematically, a list is a sequence of zero or more elements of a
same type(homogeneous).
a1, a2, a3, ......,an
n is the length of the list. If n = 0, the list is Empty.
Elements of a list can be linearly ordered according to their
position on the list. That is, we can say
ai precedes ai+1 ... and ai follows ai−1
It is also convenient to assume that there is a position following
the last element of the list.
an → followerlast
An item within a list is specified by its position in the list
M. K. A. Ariyaratne Day School 1 July 08, 2014 36 / 74
Lists
Array implementation of Lists - Array Lists
Here we are going to discuss one data structure that can be used
to implement lists on a computer’s memory.
It is the array implementation of lists. We call them Array Lists.
A linear list is a collection of elements which can be easily
represented using an array.
Here, elements of list are stored in the (contiguous) cells of an
array.
first list element’s position is determined by the index 0 in an
array.
M. K. A. Ariyaratne Day School 1 July 08, 2014 37 / 74
Lists
Array implementation of Lists - Array Lists (2)
Possible Operations on a List
List : Create an empty list
isEmpty : Determine whether the list is empty
isFull : Determine whether the list is full
getLength : Return number of items in the list
insert : Add an item to the list
delete : delete a specified item from list
find : Get the position of a specific list item
M. K. A. Ariyaratne Day School 1 July 08, 2014 38 / 74
Lists
Array implementation of Lists - Array Lists (3)
An Example
the elements of a list are34, 12, 52, 16, 12
0 1 2 3 4 5 6
34 12 52 16 12
find (52) → 2
insert (20, 3) → 34, 12, 52, 20, 16, 12
delete (52) → 34, 12, 20, 16, 12
getLength → 5
isEmpty → false
isFull → false
M. K. A. Ariyaratne Day School 1 July 08, 2014 39 / 74
Lists
Array implementation of Lists - Array Lists (4)
Advantages in Array implementation of Lists
Fast access of elements
Very memory efficient, very little memory is required other than
that needed to store the contents.
Disadvantages in Array implementation of Lists
Need to estimate size for the array from the beginning. If we need
to expand the array it is expensive (in Java) or impossible (in
some other languages). This wastes considerable space.
Also insertions and deletions are expensive because we may need
to move elements in order to execute the operation (on average
half are moved worse case all must be moved).
Better Idea : Linked ListsM. K. A. Ariyaratne Day School 1 July 08, 2014 40 / 74
Pointer Implementation of Lists
LESSON 04
Pointer Implementation ofLists
M. K. A. Ariyaratne Day School 1 July 08, 2014 41 / 74
Pointer Implementation of Lists
Pointer implementation of Lists - Linked Lists
Pointer implementation of Lists are normally known as linked lists.
They are general purpose storage structures after arrays.
In a linked list, Each data item is embedded in a node.
Each node has
1 an item
2 a reference to next node in the list
In normal linked lists, most of the time there is a dummy head
node, which points the first node in the list.
The last node normally points to NULL.
M. K. A. Ariyaratne Day School 1 July 08, 2014 42 / 74
Pointer Implementation of Lists
Pointer implementation of Lists - Linked Lists (2)
A linked list is made up of nodes.
Each node is connected to the next node by the reference ‘next’.
The ‘next’ field stores the address of the next node.
Last node’s next set to ‘NULL’.
Each node’s data is hold by ‘item’ field.
This normal Linked list is also known as “Singly Linked List”.
M. K. A. Ariyaratne Day School 1 July 08, 2014 43 / 74
Pointer Implementation of Lists
Pointer implementation of Lists - Linked Lists (3)
Relationship, Not the Position
In an array each item occupies a particular position.
This position can be directly accessed by using an index.
But, in a list the only way to find a particular element is to follow
along the chain of elements.
Null Pointer
has a value reserved for indicating that the pointer does not refer
to a valid object.
Normally used to represent conditions such as the end of a list of
unknown length or the failure to perform some action.
M. K. A. Ariyaratne Day School 1 July 08, 2014 44 / 74
Pointer Implementation of Lists
Inserting Nodes to a Linked List
A node can be inserted to a Linked List
at the beginning .
at the end .
or at a specified position in the list.
Inserting at the Beginning
Again there are two cases.
Insert a node to an empty list.
Insert a node to a beginning of an existing list.
M. K. A. Ariyaratne Day School 1 July 08, 2014 45 / 74
Pointer Implementation of Lists
Inserting Nodes to a Linked List (2)
How do you define an empty list or How do you check whether a given
list is empty?
When the Head is pointed to NULL, we say that the list is empty.
Head → NULL
Insert a node to an empty list
Following steps should be followed.1 Allocate memory for the new node.
2 Assign the data value to the item field of the new node.
3 Next of the new node should point to NULL.
(newNode.next = NULL)
4 Then head should point the new node. (Head = newNode)
M. K. A. Ariyaratne Day School 1 July 08, 2014 46 / 74
Pointer Implementation of Lists
Inserting Nodes to a Linked List (3)
Insert a node to a beginning of an existing list
Following steps should be followed.
1 Allocate memory for the new node.
2 Assign the data value to the item field of the new node.
3 Next of the new node should point to the Starting node of the
current linked list.
(newNode.next = head)
4 Then head should point the new node.
(head = newNode)
M. K. A. Ariyaratne Day School 1 July 08, 2014 47 / 74
Pointer Implementation of Lists
Inserting Nodes to a Linked List (4)
Insert a node to a beginning of an existing list (2)
Before
20 10 NULLHead
After
20 10
13
NULL
New node
Head
12
M. K. A. Ariyaratne Day School 1 July 08, 2014 48 / 74
Pointer Implementation of Lists
Inserting Nodes to a Linked List (5)
Inserting at the End
Again there are two cases.
Insert a node to an empty list.(Same as before)
Insert a node to the end of an existing list.
Insert a node to the end of an existing list
Following steps should be followed.
1 Allocate memory for the new node.
2 Assign the data value to the item field of the new node.
3 Next of the current last node should point to the new node.
(currL.next = newNode)
4 Then New node’s Next should point to Null.
(newNode.next = NULL)
M. K. A. Ariyaratne Day School 1 July 08, 2014 49 / 74
Pointer Implementation of Lists
Inserting Nodes to a Linked List (6)
Insert a node to the end of an existing list (2)
M. K. A. Ariyaratne Day School 1 July 08, 2014 50 / 74
Pointer Implementation of Lists
Inserting Nodes to a Linked List (7)
Inserting at a specified position in the list (You should provide
the position)
Following steps should be followed.
1 Allocate memory for the new node.
2 Assign the data value to the item field of the new node.
3 Find the location(index) where you need to add the Node.
4 The node before that index is known as Previous.
5 next of the new node should point the node pointed by the
previous node.
(newNode.next = previous.next)
6 Now, the next of the previous should point the new node.
(previous.next = newNode)
M. K. A. Ariyaratne Day School 1 July 08, 2014 51 / 74
Pointer Implementation of Lists
Inserting Nodes to a Linked List (8)
Inserting at a specified position in the list(2)
10 20 40 50
30
Head
New Node
Before
NULL
Prev Node
10 20 40 50
30
Head
New Node
After
NULL
Prev Node
2 1
M. K. A. Ariyaratne Day School 1 July 08, 2014 52 / 74
Pointer Implementation of Lists
Deleting Nodes from a Linked List
A node can be deleted from a Linked List
at the beginning .
at the end .
or at a specified position in the list.
Deleting from the Beginning
We are going to delete the first node in the linked list.1 If the list is empty, no deletions can be done.
2 Else, put the head to point the second node (second node is given
by head.next). That is
head = head.next
10 20 30 40 50
NULLHead
M. K. A. Ariyaratne Day School 1 July 08, 2014 53 / 74
Pointer Implementation of Lists
Deleting Nodes from a Linked List(2)
Deleting from the End
We are going to delete the last node in the linked list.
1 If the list is empty, no deletions can be done.
2 Otherwise traverse the list until the end.
3 The Next of the one before the last node should now point to null.
10 20 30 40 50
NULLHead
M. K. A. Ariyaratne Day School 1 July 08, 2014 54 / 74
Pointer Implementation of Lists
Deleting Nodes from a Linked List(3)
Deleting from a specified position in the list (You should provide
the position)
Following steps should be followed.
1 Find the location(index) where you need to delete the Node.
2 That is known as Current.
3 The node before the current is known as Previous.
4 Set the pointer (next) of the previous node to the node pointed by
the current node. In other words, set
(previous.next = current.next)
10 20 30 40 50
NULLHead
M. K. A. Ariyaratne Day School 1 July 08, 2014 55 / 74
Advanced Linked List Structures
LESSON 05
Advanced Linked ListStructures
M. K. A. Ariyaratne Day School 1 July 08, 2014 56 / 74
Advanced Linked List Structures
Introduction
In our previous discussion, we saw the singly linked list (Linked
list) and its possible operations.
This normal linked list has some drawbacks.
1 Traversing the list is available in only one direction.
2 When we need to access the end of the list, we need to traverse the
whole list.
In this lesson we introduce two new linked lists namely circular
linked lists and doubly linked lists which will overcome the
above issues.
M. K. A. Ariyaratne Day School 1 July 08, 2014 57 / 74
Advanced Linked List Structures
Circular Linked Lists
Circular Linked list is almost like a singly (normal) linked list, in
which the last node’s next contains the address of the first
node. (Last node’s next points the first node)
The difference is that there is no dummy head node. For that
we have a dummy last node, which points the last node of the
list.
Here, Next of the last node does not pointed to NULL. It is
pointed to the First node.
10 20 40 55 70
last
M. K. A. Ariyaratne Day School 1 July 08, 2014 58 / 74
Advanced Linked List Structures
Circular Linked Lists - Inserting Nodes
In Circular Linked list also we can add or delete nodes at different
positions as in singly linked lists.
But here the process is different because the operations need to
deal with the circularity of the list.
The pointer of the last node too has to be modified accordingly.
M. K. A. Ariyaratne Day School 1 July 08, 2014 59 / 74
Advanced Linked List Structures
Circular Linked Lists - Inserting Nodes (2)
Inserting at the Beginning
Following steps should be followed.1 Allocate memory for the new node. Assign the value to the data
field of the new node.
2 If the list is empty, set last = new node
10
last
new node
3 Else next of the new node should point the first node in the list andthe next of the last node should point the new node.new node.next = last.nextlast.next = new node
10 20 40 55 70
lastnew node
1
2
M. K. A. Ariyaratne Day School 1 July 08, 2014 60 / 74
Advanced Linked List Structures
Circular Linked Lists - Inserting Nodes (3)
Inserting at the EndFollowing steps should be followed.
1 Allocate memory for the new node. Assign the value to the datafield of the new node.
2 If the list is empty, set last = new node
10
last
new node
3 Else, next of the new node should point the first node and next ofthe last node should point the new node.new node.next = last.nextlast.next = new node
4 Set Last to new node.last = new node
10 20 40 55 702
new nodelast
1
3
M. K. A. Ariyaratne Day School 1 July 08, 2014 61 / 74
Advanced Linked List Structures
Circular Linked Lists - Deleting Nodes
Deleting at the Beginning
Following steps should be followed.
1 If the list is empty, no deletions are possible.
2 If there is only one node (last = last.next), free the node and set
last = Null
3 Else, next of the last node should now point the node pointed by
the current first node (we shall call it current)
last.next = current.next
10 20 40 55 70
current last
M. K. A. Ariyaratne Day School 1 July 08, 2014 62 / 74
Advanced Linked List Structures
Circular Linked Lists - Deleting Nodes(2)
Deleting at the End
Following steps should be followed.
1 If the list is empty, no deletions are possible.
2 If there is only one node (last = last.next), free the node and set
last = Null
3 Else, go on traversing till the last and set the node one before the
last(say previous) pointing the first
previous.next = last.next
4 Set the previous node as the last node
10 20 40 55 70
previous last
M. K. A. Ariyaratne Day School 1 July 08, 2014 63 / 74
Advanced Linked List Structures
Doubly Linked Lists
In a doubly linked list there are two pointers from each node. One
pointer is linked to its successor node and the other is linked to
its predecessor .
previous points to the predecessor
next points to the successor
Head
current.previous current current.next
10 20 40 55 70
NULL NULL
Doubly linked lists are useful for playing video and sound files
with rewind and “instant replay”
They are also useful for other linked data which require “rewind”
and “fast forward” of the data
M. K. A. Ariyaratne Day School 1 July 08, 2014 64 / 74
Advanced Linked List Structures
Doubly Linked Lists (2)
Each node in a doubly linked list has 3 fields namely information
holding field, left and right fields that contain pointers to nodes in
either sides.
Doubly linked list can be liner or circular.
Here we discuss the liner version only.
Also here we consider doubly linked lists with dummy head node.
M. K. A. Ariyaratne Day School 1 July 08, 2014 65 / 74
Advanced Linked List Structures
Doubly Linked Lists - Inserting Nodes
Inserting at the Beginning
Following steps should be followed.
1 Allocate memory for the new node. Assign the value to the data
field of the new node.
2 If the list is empty then the previous and next of the new node
should be assigned to null and the head is pointing the new node.
newNode.next = newNode.previous = NULL
head = newNode
Head
10 NULL
NULL
New Node
1
2
1
M. K. A. Ariyaratne Day School 1 July 08, 2014 66 / 74
Advanced Linked List Structures
Doubly Linked Lists - Inserting Nodes(2)
Inserting at the Beginning (2)
3 If the list is not empty,
1) previous of the new node should point to NULL.
newNode.previous = NULL
2) next of the new node should point the current first node(the
node pointed by the head at the moment)
newNode.next = head
3) previous of the current first node should now point the new
node.
head.previous = newNode
4) head should now point the new node.
head = newNode
M. K. A. Ariyaratne Day School 1 July 08, 2014 67 / 74
Advanced Linked List Structures
Doubly Linked Lists - Inserting Nodes(3)
Inserting at the Beginning (3)
20 30
10
Current Node
New Node
Head
NULL
NULL1
2
3
4
M. K. A. Ariyaratne Day School 1 July 08, 2014 68 / 74
Advanced Linked List Structures
Doubly Linked Lists - Inserting Nodes(4)
Inserting at the End
Following steps should be followed.
1 Allocate memory for the new node. Assign the value to the data
field of the new node.
2 If the list is empty then the previous and next of the new node
should be assigned to null and the head is pointing the new node.
3 Otherwise traverse the list until the last node and
1) next of the current last node should now point the new node
lastNode.next = newNode
2) previous of the new node should point the current last node.
newNode.previous = lastNode
3) next of the new node should point to NULL
newNode.next = NULL
M. K. A. Ariyaratne Day School 1 July 08, 2014 69 / 74
Advanced Linked List Structures
Doubly Linked Lists - Inserting Nodes(5)
Inserting at the End (2)
10 20 30 40
50
New Node
Last Node
Head NULL
1
2
3
NULL
M. K. A. Ariyaratne Day School 1 July 08, 2014 70 / 74
Advanced Linked List Structures
Doubly Linked Lists - Deleting Nodes
Deleting at the Beginning
Following steps should be followed.
1 If the list is empty, no deletions are possible.
2 Else, Let the head point to the second node.
head = head.next
Second node’s previous should point to NULL.
head.previous = NULL
20 30 40 50
NULL
NULL
Head
NULL
M. K. A. Ariyaratne Day School 1 July 08, 2014 71 / 74
Advanced Linked List Structures
Doubly Linked Lists - Deleting Nodes (2)
Deleting at the End
Following steps should be followed.
1 If the list is empty, no deletions are possible.
2 Else, Traverse the list until the end.
Let next of the node, one before the last, point to NULL
lastNode = lastNode.previous
lastNode.next = NULL
10 20 30 40
NULLNULLHead
NULL
M. K. A. Ariyaratne Day School 1 July 08, 2014 72 / 74
References
References
If you are interested in implementations in C, visit these web sites.