Download as pdf or txt
Download as pdf or txt
You are on page 1of 94

Chapter Three

Data structures and applications


• Linked lists
• Queues
• Stacks
• Trees
• Graphs
1/25/2023 1
Data structures and applications
• Structures are aggregate data types built using elements of primitive data types.
• Structure are defined using the struct keyword:
E.g. struct Time{
int hour;
int minute;
int second;
};
The struct keyword creates a new user defined data type that is used to declare
variables of an aggregate data type.
Structure variables are declared like variables of other types.
Syntax:
struct ;
E.g. struct Time timeObject, struct Time *timeptr;

1/25/2023 2
Accessing Members of Structure Variables
• The Dot operator (.): to access data members of structure variables.
• The Arrow operator (->): to access data members of pointer variables
pointing to the structure.
E.g. Print member hour of timeObject and timeptr. cout<< timeObject.hour; or
cout<hour;

TIP: timeptr->hour is the same as (*timeptr).hour.


The parentheses is required since (*) has lower precedence than (.)

• Self-Referential Structures:
Structures can hold pointers to instances of themselves.
struct list{
char name[10];
int count;
struct list *next;
};
However, structures cannot contain instances of themselves.
1/25/2023 3
Singly Linked Lists
• Linked lists are the most basic self-referential structures. Linked lists allow
you to have a chain of structs with related data.
• Array vs. Linked lists: Arrays are simple and fast but we must specify their
size at construction time. This has its own drawbacks. If you construct an
array with space for n, tomorrow you may need n+1.Here comes a need
for a more flexible system?
• Advantages of Linked Lists: Flexible space use by dynamically allocating
space for each element as needed. This implies that one need not know
the size of the list in advance. Memory is efficiently utilized.
• A linked list is made up of a chain of nodes. Each node contains:
• The data item, and
• A pointer to the next node

1/25/2023 4
Creating Linked Lists in C++
• A linked list is a data structure that is built from structures and pointers.
• It forms a chain of "nodes" with pointers representing the links of the chain
and holding the entire thing together.
• A linked list can be represented by a diagram like this one:

• This linked list has four nodes in it, each with a link to the next node in the
series.
• The last node has a link to the special value NULL, which any pointer (whatever
its type) can point to, to show that it is the last link in the chain.
• There is also another special pointer, called Start (also called head), which
points to the first link in the chain so that we can keep track of it.

1/25/2023 5
Defining the data structure for a linked list
• The key part of a linked list is a structure, which holds the data for each node
(the name, address, age or whatever for the items in the list), and, most
importantly, a pointer to the next node. Here we have given the structure of a
typical node:
struct node {
char name[20]; // Name of up to 20 letters
int age;
float height; // In metres
node *nxt; // Pointer to next node
};
struct node *start_ptr = NULL;
• The important part of the structure is the line before the closing curly brackets.
This gives a pointer to the next node in the list.
• This is the only case in C++ where you are allowed to refer to a data type (in
this case node) before you have even finished defining it!
• We have also declared a pointer called start_ptr that will permanently point to the
start of the list.
• To start with, there are no nodes in the list, which is why start_ptr is set to NULL.
1/25/2023 6
Adding a node to the list
• The first problem that we face is how to add a node to the list.
• For simplicity's sake, we will assume that it has to be added to the end
of the list, although it could be added anywhere in the list (a problem
we will deal with later on).
• Firstly, we declare the space for a pointer item and assign a temporary pointer
to it. This is done using the new statement as follows:
temp = new noe;

• We can refer to the new node as *temp, i.e. "the node that temp points to". When the fields of this structure
are referred to, brackets can be put round the *temp part, as otherwise the compiler will think we are trying to
refer to the fields of the pointer.
• Alternatively, we can use the arrow pointer notation.
1/25/2023 7
… cont
• Having declared the node, we ask the user to fill in the details of the
person, i.e. the name, age, address or whatever:
cout << "Please enter the name of the person: ";
cin >> temp->name;
cout << "Please enter the age of the person : ";
cin >> temp->age;
cout << "Please enter the height of the person : ";
cin >> temp->height;
temp->nxt = NULL;
• The last line sets the pointer from this node to the next to NULL, indicating that
this node, when it is inserted in the list, will be the last node.
• Having set up the information, we have to decide what to do with the pointers.
• Of course, if the list is empty to start with, there's no problem - just set the Start
pointer to point to this node (i.e. set it to the same value as temp):
if (start_ptr == NULL)
start_ptr = temp;

1/25/2023 8
… cont
• It is harder if there are already nodes in the list. In this case, the secret is to declare a second pointer, temp2, to step
through the list until it finds the last node.

temp2 = start_ptr; // We know this is not NULL - list not empty!


while (temp2->nxt != NULL) {
temp2 = temp2->nxt; // Move to next link in chain
}
• The loop will terminate when temp2 points to the last node in the chain, and it knows when this happened
because the nxt pointer in that node will point to NULL.
• When it has found it, it sets the pointer from that last node to point to the node we have just declared:
temp2->nxt = temp;

1/25/2023 9
… cont
The link temp2->nxt in this diagram is the link joining the last two nodes. The full code for adding a node at the end of the
list is shown below, in its own little function:
void add_node_at_end () {
node *temp, *temp2; // Temporary pointers // Reserve space for new node and fill it with data
temp = new node;
cout << "Please enter the name of the person: ";
cin >> temp->name;
cout << "Please enter the age of the person : ";
cin >> temp->age;
cout << "Please enter the height of the person : ";
cin >> temp->height; temp->nxt = NULL; // Set up link to this node
if (start_ptr == NULL) start_ptr = temp;
else
{ temp2 = start_ptr; // We know this is not NULL - list not empty!
while (temp2->nxt != NULL) {
temp2 = temp2->nxt; // Move to next link in chain
}
temp2->nxt = temp;
} }

1/25/2023 10
Displaying the list of nodes
• Having added one or more nodes, we need to display the list of nodes on the screen.
• This is comparatively easy to do. Here is the method:
1. Set a temporary pointer to point to the same thing as the start pointer.
2. If the pointer points to NULL, display the message "End of list" and stop.
3. Otherwise, display the details of the node pointed to by the start pointer.
4. Make the temporary pointer point to the same thing as the nxt pointer of the node it is currently indicating.
5. Jump back to step 2.
• The temporary pointer moves along the list, displaying the details of the nodes it comes across.
• At each stage, it can get hold of the next node in the list by using the nxt pointer of the node it is currently
pointing to.
• Here is the C++ code that does the job:
temp = start_ptr;do {
if (temp == NULL)
cout << "End of list" << endl;
else
{ // Display details for what temp points to
cout << "Name : " << temp->name << endl;
cout << "Age : " << temp->age << endl;
cout << "Height : " << temp->height << endl;
cout << endl; // Blank line // Move to next node (if present)
temp = temp->nxt;
} } while (temp != NULL);

• Check through this code, matching it to the method listed above. It helps if you draw a diagram on paper of a
linked list and work through the code using the diagram.
1/25/2023 11
Navigating through the list
• One thing you may need to do is to navigate through the list, with a pointer that moves backwards and
forwards through the list, like an index pointer in an array.
• This is certainly necessary when you want to insert or delete a node from somewhere inside the list, as you
will need to specify the position.
• We will call the mobile pointer current. First of all, it is declared, and set to the same value as the start_ptr pointer:
node *current;current = start_ptr;
• Notice that you don't need to set current equal to the address of the start pointer, as they are both pointers. The statement
above makes them both point to the same thing:

• It's easy to get the current pointer to point to the next node in the list (i.e. move from left to right along the
list). If you want to move current along one node, use the nxt field of the node that it is pointing to at the
moment:
current = current->nxt;
In fact, we had better check that it isn't pointing to the last item in the list. If it is, then there is no next node to move to:
if (current->nxt == NULL)
cout << "You are at the end of the list." << endl;
else
current = current->nxt;
1/25/2023 12
…cont
• Moving the current pointer back one step is a little harder. This is because we have no way of moving back a step
automatically from the current node.
• The only way to find the node before the current one is to start at the beginning, work our way through and stop when we
find the node before the one we are considering at the moment.
• We can tell when this happens, as the nxt pointer from that node will point to exactly the same place in memory as the
current pointer (i.e. the current node).

• First of all, we had better check to see if the current node is also first the one. If it is, then there is no "previous" node to
point to. If not, check through all the nodes in turn until we detect that we are just behind the current one (Like a
pantomime - "behind you!")
if (current == start_ptr)
cout << "You are at the start of the list" << endl;
else {
node *previous; // Declare the pointer
previous = start_ptr;
while (previous->nxt != current) {
previous = previous->nxt;
}
1/25/2023
current = previous; 13
}
…cont
• The else clause translates as follows:
• Declare a temporary pointer (for use in this else clause only). Set it equal to the start pointer. All the time that it is not
pointing to the node before the current node, move it along the line. Once the previous node has been found, the current
pointer is set to that node - i.e. it moves back along the list.
• Now that you have the facility to move back and forth, you need to do something with it. Firstly, let's see if we can alter
the details for that particular node in the list:
cout << "Please enter the new name of the person: ";
cin >> current->name;
cout << "Please enter the new age of the person : ";
cin >> current->age;
cout << "Please enter the new height of the person : ";
cin >> current->height;
• The next easiest thing to do is to delete a node from the list directly after the current position. We have to use a
temporary pointer to point to the node to be deleted. Once this node has been "anchored", the pointers to the
remaining nodes can be readjusted before the node on death row is deleted. Here is the sequence of actions:

1. Firstly, the temporary pointer is assigned to the node after the current one. This is the node to be deleted:
Current Temp

NULL

1/25/2023 14
…cont
2. Now the pointer from the current node is made to leap-frog the next node and point to the one after that:
current temp

NULL

3. The last step is to delete the node pointed to by temp.


• Here is the code for deleting the node. It includes a test at the start to test whether the current node is the last one in
the list:
if (current->nxt == NULL)
cout << "There is no node after current" << endl;
else {
node *temp;
temp = current->nxt;
current->nxt = temp->nxt; // Could be NULL
delete temp;
}
• Here is the code to add a node after the current one. This is done similarly, but we haven't illustrated it with
diagrams:

1/25/2023 15
…cont
if (current->nxt == NULL)
add_node_at_end();
else {
node *temp;
new temp;
get_details(temp); // Make the new node point to the same thing as
// the current node
temp->nxt = current->nxt; // Make the current node point to the new link
// in the chain
current->nxt = temp;
}
• We have assumed that the function add_node_at_end() is the routine for adding the node to the
end of the list that we created near the top of this section. This routine is called if the
current pointer is the last one in the list so the new one would be added on to the end.
• Similarly, the routine get_temp(temp) is a routine that reads in the details for the new node
similar to the one defined just above. ... and so...

1/25/2023 16
Deleting a node from the list
• When it comes to deleting nodes, we have three choices: Delete a node from the start of the list, delete one
from the end of the list, or delete one from somewhere in the middle. For simplicity, we shall just deal with
deleting one from the start or from the end.
• When a node is deleted, the space that it took up should be reclaimed. Otherwise the computer will eventually run out of
memory space. This is done with the delete instruction:
delete temp; // Release the memory pointed to by temp
• However, we can't just delete the nodes willy-nilly as it would break the chain. We need to reassign the pointers and then
delete the node at the last moment. Here is how we go about deleting the first node in the linked list:
temp = start_ptr; // Make the temporary pointer // identical to the start pointer

• Now that the first node has been safely tagged (so that we can refer to it even when the start pointer has been
reassigned), we can move the start pointer to the next node in the chain:
start_ptr = start_ptr->nxt; // Second node in chain.

1/25/2023 17
…cont
delete temp; // Wipe out original start node

Here is the function that deletes a node from the start:


void delete_start_node() {
node *temp;
temp = start_ptr;
start_ptr = start_ptr->nxt;
delete temp;
}
• Deleting a node from the end of the list is harder, as the temporary pointer must find where the end of the list is by hopping
along from the start. This is done using code that is almost identical to that used to insert a node at the end of the list.
• It is necessary to maintain two temporary pointers, temp1 and temp2.
• The pointer temp1 will point to the last node in the list and temp2 will point to the previous node.
• We have to keep track of both as it is necessary to delete the last node and immediately afterwards, to set the nxt pointer of
the previous node to NULL (it is now the new last node).
1/25/2023 18
…cont
1. Look at the start pointer. If it is NULL, then the list is empty, so print out a "No nodes to delete" message.
2. Make temp1 point to whatever the start pointer is pointing to.
3. If the nxt pointer of what temp1 indicates is NULL, then we've found the last node of the list, so jump to step 7.
4. Make another pointer, temp2, point to the current node in the list.
5. Make temp1 point to the next item in the list.
6. Go to step 3.
7. If you get this far, then the temporary pointer, temp1, should point to the last item in the list and the other temporary
pointer, temp2, should point to the last-but-one item.
8. Delete the node pointed to by temp1.
9. Mark the nxt pointer of the node pointed to by temp2 as NULL - it is the new last node.

Let's try it with a rough drawing. This is always a good idea when you are trying to understand an abstract data type.
Suppose we want to delete the last node from this list:

• Firstly, the start pointer doesn't point to NULL, so we don't have to display a "Empty list, wise guy!" message. Let's get
straight on with step2 - set the pointer temp1 to the same as the start pointer:

1/25/2023 19
…cont

• The nxt pointer from this node isn't NULL, so we haven't found the end node. Instead, we set the pointer temp2 to the same
node as temp1

• and then move temp1 to the next node in the list:

• Going back to step 3, we see that temp1 still doesn't point to the last node in the list, so we make temp2 point to what
temp1 points to

1/25/2023 20
…cont
• and temp1 is made to point to the next node along:

• Eventually, this goes on until temp1 really is pointing to the last node in the list, with temp2 pointing to the
penultimate node:

• Now we have reached step 8. The next thing to do is to delete the node pointed to by temp1

1/25/2023 21
…cont
• and set the nxt pointer of what temp2 indicates to NULL:

• We suppose you want some code for all that! All right then ....
void delete_end_node() {
node *temp1, *temp2;
if (start_ptr == NULL)
cout << "The list is empty!" << endl;
else {
temp1 = start_ptr;
while (temp1->nxt != NULL) {
temp2 = temp1;
temp1 = temp1->nxt;
}
delete temp1;
temp2->nxt = NULL;
} }
1/25/2023 22
…cont
• The code seems a lot shorter than the explanation!
• Now, the sharp-witted amongst you will have spotted a problem. If the list only contains one node, the code above will
malfunction.
• This is because the function goes as far as the temp1 = start_ptr statement, but never gets as far as setting up temp2.
• The code above has to be adapted so that if the first node is also the last (has a NULL nxt pointer), then it is deleted and the
start_ptr pointer is assigned to NULL. In this case, there is no need for the pointer temp2:
void delete_end_node() {
node *temp1, *temp2;
if (start_ptr == NULL)
cout << "The list is empty!" << endl;
else {
temp1 = start_ptr;
if (temp1->nxt == NULL) // This part is new!
{
delete temp1;
start_ptr = NULL;
}
else {
while (temp1->nxt != NULL) {
temp2 = temp1;
temp1 = temp1->nxt;
}
delete temp1;
temp2->nxt = NULL;
1/25/2023 } } } 23
Queues
It is a linear data structure.

A list where additions and deletions are done at opposite ends.

Addition is done at the rear/last whereas deletion at the front/first of the queue

FIFO: Accessing the elements of queues follows a First In First Out (FIFO) order.

The first element inserted into the queue is the first element to be removed

Queue uses two pointers/indices to keep track of information/data.


Front/head
Rear/tail

1/25/2023 24
Queue(cont….)
Has two basic operations:

Enqueue(elt) : Inserting data at the rear of the queue.

Dequeue: Removing data at the front of the queue.

Analogy: consider a line of people waiting to be served:

New arrivals join the rear of the line.

People leave the line at the front to beserved.

People are served in the order that they arrive(FIFO)

1/25/2023 25
Example

1/25/2023 26
Queue Implementation
Like stack, queue can be implemented as arrays or linked lists.
Array Implementation of Queue
We need to have two integer variables that tell:
the index of the front element
the index of the rearelement

When adding elements to the queue, the index rearincreases.


When deleting elements from the queue, the index front also increases.
Each time we enqueue an element, the queue grows to the right (ie. larger indices)

Each time an element is dequeued, the queue shrinks from the left.
Thus, the entire queue will slowly drift to the right.
Eventually, we will reach the end of the array, and no longer be able to add elements to the
queue even there are space on the left hand side of thearray.

1/25/2023 27
Queue implementation (cont…)
To solve this problem, consider a queue of people waiting to beserved.
Each time someone leaves the queue from the front, everyone else shuffle forward to fill
the gap.
Similarly, for an array based queue, each time we dequeued an element,

we could shift each element of the queue one index to the left.
A more efficient solution is to use a circular array.
The array wraps around, so that if we reach the end of the array we start enqueueing
elements at thestart.
If the queue is full, we still won’t be able to enqueue any more elements.

1/25/2023 28
Circular Queues
• In circular queues if an attempt is made to insert another element into
the queue the element will be stored at the position 0, if
• Example that position is empty.

enqueue - 60

1/25/2023 29
Circular Array(cont… )

1/25/2023 30
Queue implementation(cont…)

1/25/2023 31
Queue implementation(cont…….)

// counter is the number of items in the queue.

1/25/2023 32
Queue implementation(cont…….)

1/25/2023 33
Stack: What is a stack?
 It is an ordered group of homogeneous items of elements.

 Elements are added to and removed from the top of the stack (the most recently
added items are at the top of the stack).

 The last element to be added is the first to be removed (LIFO: Last In, First Out).

 Think of a stack of plates at a salad bar.

 We can add to the top of the stack (push)

 We can remove the top plate (pop)

 To access the nth plate, we must first remove the n-1 plates above it.

1/25/2023 34
Stack continue……….
Example

Which is the first element to pick up?

1/25/2023 35
1/25/2023 36
Managing Top element

1/25/2023 37
Stack Specification
 Definitions: (provided by the user)
MaxItem: Max number of items that might be on the stack

ItemType: Data type of items on the stack


 Operations
Push (ItemType newItem)

Pop (ItemType& item) (or pop and top)

Create()-it make the stack empty


 Stack overflow
The condition resulting from trying to push an element onto a full stack.
 Stack underflow
The condition resulting from trying to pop an empty stack.

1/25/2023 38
Push operation
• Needs argument/element to be pushed
push(ItemType newItem)

• Function: Adds newItem to the top of the stack.

• Preconditions: Stack has been initialized and is not full.

• Post conditions: newItem is at the top of the stack(the value of “TOP” is


incremented by 1,top=top+1)

1/25/2023 39
Pop operation
• Arguments are not required for pop operation.

• Has return a value which is going to be deleted.

• Function: Removes top item from stack and returns it in item.

• Preconditions: Stack has been initialized and is not empty.

• Post conditions: Top element has been removed from stack(the value of
“TOP” is decremented by 1,top=top-1)

1/25/2023 40
Stack Implementation
Stack can be implemented in two ways

 Array implementation

 Linked list implementation

Array implementation
 The elements of the stack will be placed in an array.

 A variable called top holds the index of the elements entered last.

 Top will be initially -1 to indicate the list is empty.

 Then we define function for each operation stack will do.

1/25/2023 41
Stack Implementation (cont.)
Create
 Means stack empty
 Simply make top=-1
int pop(){
Void create(){
int pop_Val;
top=-1; }
if(top==-1)
const int size=10;
int stack[size];
cout<<“Under flow”;
int top= -1; else{
Void push(int item){ pop_val=stack[top];
if (top==size-1) top=top-1
cout<<“over flow” }
else{ Return (pop_val);
top=top+1; }
stack[top]=item; }

1/25/2023
} 42
Stack Implementation (cont….)
Linked list implementation
As you know, the array implementation of stack has certain disadvantages:
1.Limited stack size

2.Inefficient memory usage

 To avoid these problems we are implemented stacks in the form of linked list.

 The elements will be placed at different memory location and linked using their
address. Then we hold the address of;
 the first element

 the last element


1/25/2023 43
Push operation in LL
 Pushing an element means adding an element next to current last element.
 The added element become the last element.
 If there are no elements, the new element will be the first element
and last element.
Example:

1/25/2023 44
Stack implementation using LL
struct stack{
int item;
stack*next;
};
stack*start=null,*top=null;
Void push(int x){
stack*temp=new stack;
temp->item=x;
temp->next=null;
if(start==null)
start=top=temp;
else{
top->next=temp;
top=temp;}}

1/25/2023 45
Pop operation in LL
 Popping an element means returning the value of the top element and deleting it from the stack.

 While deleting the last element, the element before the last element should be made last.

 Hence we need the address of


The last element(to delete)
The element before last (to make it last)
 When we pop:

 Return the top element


 Delete the element
 Make the element before last top

1/25/2023 46
Stack implementation using LL
void pop(){

if(start==null)
cout<<“under flow”;
else{
stack*temp;
temp=start;
if(start==top){
cout<<“The poped_val is”<<top->elt;
delete temp;
start=top=null;}
else{
stack*temp2;
While(temp->next!=null){
temp2=temp;
temp=temp->next;}
cout<<“The poped_val is”<<top->elt;
delete temp;
temp2->next=null;
top=temp2;}

}
1/25/2023 47
Create operation
Void create(){
top=start=null;
}

1/25/2023 48
Tree
A tree is a set of nodes and edges that connect pairs of nodes.
 It is an abstract model of a hierarchical structure. (non linear data structure )
 One node distinguished as root.
 Every node C except the root is connected from exactly other node P.
P is C‘s parent, and C is one of C's children.
 There is a unique path from the root to the each node.
 The number of edges in a path is the length of the path.
A

B E F G

C D H I J

K L M
1/25/2023 49
Continue……
A

Tree Terminologies.
B E F G

C D H I J

K L M
Root:a node without a parent. A
Internal node: a node with at least one child. A, B, F, I, J
External (leaf) node: a node without a child. C, D, E, H, K, L, M, G
Ancestors of a node:parent, grandparent, grand-grandparent, etc of a node.
Ancestors of K A, F, I
Descendants of a node: children, grandchildren, grand-grandchildren etc of a node.
Descendants of F H, I, J, K, L, M

1/25/2023 50
Continue…..
Depth of a tree/Height of a tree: the length of the longest path from the root to any other node. Or the
depth of the deepest node. 3
Sub tree: a tree consisting of a node and its descendants.
Degree: The degree of a node is the number of children it has.
Degree of leaf is zero.
Nodes that have degree ZERO are called Leaf nodes or Terminal nodes.

H I J

K L M

1/25/2023 51
Binary Tree
Binary tree is a tree in which no node can have more than two children or a tree
in which each node has at most two children called left child and right child.
Binary tree is either empty, or it consists of a node called the root together with
two binary trees called the left sub-tree and the right sub-tree.

1/25/2023 52
Continue…..
Complete binary tree: a binary tree in which the length from the root to any leaf node is
either h or h-1 where h is the height of the tree. The deepest level should also be filled
from left to right.

1.Representation of binary tree


Binary tree can also be represented in two ways.
•Array representation
•Linked representation
Array representation:-
Consider the following binary tree.
1/25/2023 53
Continue……

1/25/2023 54
continue…….
Linked Implementation:
In linked list representation each element is represented by a node that has exactly two link fields called
one is left pointer (Left) and the other is right pointer (Right) and data field called info.
Declaration:-
Struct node {
int info;
node*right;
node*left;
};
node*rootptr=NULL;
Each edge in the drawing of a binary tree is represented by a pointer from the
parent node to child node.
This pointer is placed in appropriate link field of the parent node.
Since a n element binary tree has exactly n-1 edges ,there will be 2n-(n-1)=n+1 link fields that have Null
value.

1/25/2023 55
Binary search tree (ordered binary tree)

A binary tree that may be empty, but if it is not empty, it satisfies the following.
• Every node has a key and no two elements have the same key.
• The keys in the right subtree are larger than the keys in the root.
• The keys in the left subtree are smaller than the keys in the root.
• The left and the right subtrees are also binary search trees.

1/25/2023 56
Binary search tree (ordered binary tree)

1/25/2023 57
… cont

1/25/2023 58
… cont
Operations on Binary Search Tree
• Inserting a new node
• Searching an elements
• Finding smallest element
• Finding largest element
• Deleting a node
• Traversing all elements
Consider the following definition of binary search tree.
struct Node
{
int Num;
Node * Left, *Right;
};
Node *root=NULL;

1/25/2023 59
… cont

1/25/2023 60
Traversing

1/25/2023 61
… cont

1/25/2023 62
Deletion operation

1/25/2023 63
Cont..

1/25/2023 64
Cont..
Case 2: Deleting a node having only one child,
Approach 1: Deletion by merging – one of the following is done

• If the deleted node is the left child of its parent and the deleted node has only the left child, the left child
of the deleted node is made the left child of the parent of the deleted node.
• If the deleted node is the left child of its parent and the deleted node has only the right child, the right
child of the deleted node is made the left child of the parent of the deleted node.
• If the deleted node is the right child of its parent and the node to be deleted has only the left child, the
left child of the deleted node is made the right child of the parent of the deleted node.
• If the deleted node is the right child of its parent and the deleted node has only the right child, the right
child of the deleted node is made the right child of the parent of the deleted node.

1/25/2023 65
GRAPH
• Types of Graph
• Terminology
• Storage Structure

1/25/2023 66
Graph
A graph is a collection of nodes (or vertices, singular is vertex) and
edges (or arcs)

 Each node contains an element


Each edge connects two nodes together (or possibly the
same node to itself) and may

contain an edge attribute A


B C

D E

F
G
1/25/2023 67
Formal definition of graph

A graph G is defined as follows:

G=(V,E)

V(G): a finite, nonempty set of vertices

E(G): a set of edges (pairs of vertices)

1/25/2023 68
Types of graph

Directed graph (digraph)

Undirected graph (graph)

1/25/2023 69
Undirected graph
 An undirected graph is one in which the edges do
not have a direction

 ‘graph’ denotes undirected graph.

G1 = ( 4, 6)
 Undirected graph:
V(G1) = { 0, 1, 2 , 3 }
 ( v1, v2 ) in E is un-ordered. E(G1) = { (0,1), (0,2), (0,3
 (v1,v2) and (v2, v1) represent (1,2), (1,3), (2,3) }

the same edge.


1/25/2023 70
Directed graph
 Directed graph is one in which the edges have a direction

 Also called as ‘digraph’


 Directed graph:
 < v1, v2 > in E is ordered.
 <V1,v2> and <v2, v1> represent

the two different edges. G3 = (3, 3)


V(G3) = { 0,1,2 }
E(G3) = { <0,1> , <1,0> , <1,2>

1/25/2023 71
Complete graph
A complete graph is a graph that has the maximum

number of edges .

 for undirected graph with n vertices, the maximum number of edges is

n(n-1)/2

 for directed graph with n vertices, the maximum number of edges is

n(n-1)

1/25/2023 72
Complete graph

No.of edges = n(n-1)/2 No.of edges = n(n-1)/2 No.of edges = n(n-1


= 4*3/2 = 7*6/2 = 3*2
= 12/2 = 42/2 =6
=6 = 21
1/25/2023 73
Adjacent and Incident

 If (v0, v1) is an edge in an undirected graph,

– v0 and v1 are adjacent

– The edge (v0, v1) is incident on vertices v0 and v1

 If <v0, v1> is an edge in a directed graph

– v0 is adjacent to v1, and v1 is adjacent from v0

– The edge <v0, v1> is incident on vertices v0 and v1

1/25/2023 74
Sub- graph
A sub-graph of G is a graph G’ such that

 V(G’) is a subset of V(G)

 E(G’) is a subset of E(G)

1/25/2023 75
Path
 A path is a list of edges such that each node is the predecessor of the next node
in the list

 A path from vertex vp to vertex vq in a graph G, is a sequence of vertices, vp, vi1,


vi2, ..., vin, vq, such that (vp, vi1), (vi1, vi2), ..., (vin, vq) are edges in an
undirected graph

 The length of a path is the number of edges on it

 A simple path is a path in which all vertices,


except possibly the first and the last, are distinct

1/25/2023 76
Cycle
A cycle is a path whose first and last nodes are the

same

- A cyclic graph contains at least one cycle

- An acyclic graph does not contain any c ycles

cyclic graph acyclic graph


1/25/2023 77
Connected component
 In an undirected graph G, two vertices, v0 and v1,

are connected if there is a path in G from v0 to v1

 An undirected graph is connected if, for every pair

of distinct vertices vi, vj, there is a path from vi to vj

 A connected component of an undirected graph is a

maximal connected sub-graph.

1/25/2023 78
Strongly connected

 A directed graph is strongly connected if there is a

directed path from vi to vj and also from vj to vi.

 A strongly connected component is a maximal sub-

graph that is strongly connected

1/25/2023 79
Tree
A tree is a graph that is

 connected

 acyclic.

1/25/2023 80
Degree
 The degree of a vertex is the number of edges incident to that vertex
 For directed graph,
 the in-degree of a vertex v is the number of edges that have v as
the head
 the out-degree of a vertex v is the number of
edges that have v as the tail
 if di is the degree of a vertex i in a graph G with
n vertices and e edges, the number of edges is

n 1
e  (  di ) / 2
0
1/25/2023 81
Degree - graph

1/25/2023 82
Degree - digraph

1/25/2023 83
Graph Representation

 Adjacency Matrix

 Adjacency Lists

1/25/2023 84
Adjacency matrix
 Let G=(V,E) be a graph with n vertices.
 The adjacency matrix of G is a two-dimensional n by n array, say adj_mat

 If the edge (vi, vj) is in E(G), adj_mat[i][j]=1

 If there is no edge in E(G), adj_mat[i][j]=0


 The adjacency matrix for an undirected graph is symmetric

 the adjacency matrix for a digraph need not be


symmetric

1/25/2023 85
20
Adjacency matrix - graph
0 1 2 3
0 0 1 1 1
1 0 1 1 
1

2 1 1 0 1
 
3 1 1 1 0
0 1 2 3 4 5 6 7
0
1
2
3
4
5
6
1/25/2023 86
7 21
Adjacency matrix - digraph

0 1 2
0 0 1 0
 
1 1 0 1 
2 0 0 0

1/25/2023 87
Merits of Adjacency Matrix
 From the adjacency matrix, to determine the connection of vertices is easy

 The degree of a vertex isadj_ mat[i][j] n1

• j0

 For a digraph,
 the row sum is the out_degree

 the column sum is the in_degree

n1 n1
ind(vi)   A[ j,i] outd(vi)   A[i, j]
j0 j0
1/25/2023 88
Demerits of adjacency matrix

 Storage complexity: O(|V|2)

 Difficult to insert and delete nodes.

1/25/2023 89
Adjacency list

 To overcome the problem arise in the adjacency

matrix, linked list can be used

 The adjacency list contains two lists

1. node list

2. edge list

1/25/2023 90
Adjacency list – graph

1/25/2023 91
Adjacency list - digraph

Adjacency list Inverse Adjacency list

1/25/2023 92
Merits of adjacency list
 degree of a vertex in an undirected graph

 number of nodes in adjacency list

 out-degree of a vertex in a directed graph

 number of nodes in its adjacency list

 in-degree of a vertex in a directed graph

 traverse the whole data structure


 Simple way to find out in-degree of vertex in a directed graph

1/25/2023
 Represent the graph in inverse adjacency list 28
93
Thank You!

1/25/2023 94

You might also like