Beruflich Dokumente
Kultur Dokumente
STRUCTURES
AND
ALGORITHMS
1
Stacks
Queues
Linked lists
Trees
Graphs
Introduction to Data
Structures
Data is a set of elementary items.
The data structures deal with the study of how the
Introduction to Data
Structures
add
delete
find
Lifetime Of A Variable
is a run-time concept
period of time during which a variable has memory space
associated with it
automatic data
run-time stack - activation records
added and removed as program runs
(expands and shrinks in an orderly
LIFO manner)
heap data
Heap Variables
Space for heap variables is allocated from an area of
10
11
variables.
12
own identifier.
Each item is called a member of the structure.
To access the members of a structure, we need to create
13
14
15
17
Stack
ptr
Heap
100
100
Name
Marks
18
Self-Referential Structures
Suppose, you have been given a task to store a list of
21
Self-Referential Structures
However, when runtime variables of a particular type
Self-Referential Structures
A self-referential structure is so defined that one of the
variable of the same type, thus forming a noncontiguous, loosely linked data structure.
This self-referential data structure is also called a linked
list.
23
24
25
LINEAR DATA
STRUCTURES
26
STACKS
27
Objectives
Define a stack
Describe the operations on a stack
Implement a stack as a special case of a linked list
Describe applications of stacks
28
What is a Stack?
A stack is a data structure in which insertions and
29
What is a Stack?
You would have noticed that whenever a book is placed
30
What is a Stack?
top
top
10
12
top
14
10
12
10
8
6
4
2
(a)
(b)
(c)
31
Characteristics of a Stack
When you add an element to the stack, you say that you
Characteristics of a Stack
Since the definition of the stack provides for the
33
Operations on Stacks
Some of the typical operations performed on stacks are:
create (s)
push (s, i)
stack s
pop (s)
Implementation of Stacks
An array can be used to implement a stack.
But since array size is defined at compile time, it cannot
35
Implementation of Stacks
An ideal implementation for a stack is a linked list that
36
37
38
39
Implementing push( )
push( )
{
struct stack * new;
char ch;
ch = y;
while (ch = = y)
{
new = makenode( );
/* checking for an empty stack */
if ( top = = null)
{
top = new;
}
40
Implementing push( )
else
{
new->next = top;
top = new;
}
printf("%s","Want to add more nodes\n");
scanf( "%c", &ch );
fflush( stdin );
} /* end of while */
} /* end of push( )
41
info
top
next
info
next
42
43
Implementing pop( )
pop( )
{
struct stack * temp;
int x;
/* check for an empty stack */
if (top = = null)
{
printf (Cannot remove nodes from an empty stack */
exit( );
}
44
Implementing pop( )
else
{
temp = top;
x = top->info;
top = top->next;
free( temp);
return x;
}
45
top
next
46
Applications of Stacks
As a stack is a LIFO structure, it is an appropriate data
47
Applications of Stacks
As an example, let main( ) call a( ). Function a( ), in turn,
48
Applications of Stacks
When a( ) is called, its calling information is pushed on to
49
Applications of Stacks
Then, when b( ) calls c( ), c( )s calling information is
Applications of Stacks
Finally, when a( ) completes, the stack is again popped
invokes itself.
51
Queues
52
Objectives
In this session, you will learn to:
Define a queue
Describe the operations on a queue
Implement a queue as a special case of a linked list
Describe applications of queues
53
Defining a Queue
A Queue is a special kind of data structure in which
54
Defining a Queue
Every time the student at the front of the queue
front
front
rear
(a)
rear
(b)
rear
front
(c)
56
Queue Operations
To complete this definition of a queue, you must specify
Queue Operations
create(q) which creates q as an empty queue
enq(i)
adds the element i to the rear of the queue
Implementing Queues
Linked lists offer a flexible implementation of a queue
59
Implementing Queues
Queue functionality of a linked list can be achieved by
implementation of a queue.
rear
front
60
61
Queue Operations
You can determine whether a queue is empty or not by checking
62
63
64
65
67
front
4
next
7
next
8
next
New
68
69
front
70
Applications of Queues
Queues are also very useful in a time-sharing multi-user
71
Applications of Queues
Whenever the CPU is free, it executes the job that is at
Disadvantages of a Queue
The operations such as inserting an element and deleting an
Circular Queue
In circular queue, the elements of a given queue can be
shown in the next slide [fig (a)]. In this case, the rear end
identified by r is 0 and the front end identified by f is also
0. Since only r is incremented upon item insertion, its
initial value has to be -1 and f should be 0.
75
Pictorial Representation of
Circular Queue
2
10
1
10
f
(a)
f, r
3
30
2 r
20
10
20
30
(b)
10
f
40
30
20
50
10
(c)
10
20
30
40
4
50
Pictorial Representation of
Circular Queue (contd)
2
3
40
30
(d)
40
50
30
60
1
60
0
50
40
2
30
50
30
40
4
50
(e)
r
After inserting 60
77
Pictorial Representation of
Circular Queue (contd)
The configuration shown in fig (b) is obtained on
or r = (r+1)%QUEUE_SIZE;
Pictorial Representation of
Circular Queue (contd)
In case of items being deleted, as in an ordinary queue,
79
Priority Queue
A special type of queue in which items can be
80
LINKED LISTS
82
Objectives
Describe linked lists
Types of linked lists
Write code to:
Create a sorted linked list,
Insert nodes into a sorted linked list
Traverse a linked list
Delete nodes from a linked list
Doubly linked lists
Circular linked lists
83
Linked Lists An
Introduction
Linked lists were developed in 1955-56 by Allen Newell, Cliff
Linked List
Subsequent nodes are accessed via the link-pointer
Link pointer in the last node is set to null to mark the lists
end
85
Forward pointer of the last node points to the first node and
backward pointer of the first node points to the last node
86
88
slide:
89
100
Heap
100
75
marks
140
140
next
85
marks
180
180
next
95
marks
230
next
100 x
marks
next
90
simple.
Algorithm for placing the new element at the head of the
list:
92
simple.
Assuming a new node X is being inserted between
nodes N1 and N2
Algorithm for inserting a new node between two nodes in
the list
93
94
1.
2.
3.
96
97
98
100
101
103
104
Searching a Value in a
Linked List
struct marks_list *search( int val)
{
for( ptr = start; (ptr); ptr = ptr->next)
{
if (val = = ptr-> marks)
return ptr;
}
105
106
Objectives
In this session, you will learn to:
Describe the need for, and advantages of a
109
search for a value in a linked list from the end of the list.
110
Properties of a Doubly
Linked
List
say, next pointing to the next node in the list, and another
say, prior pointing to the previous node in the list.
Therefore, traversing a doubly linked list in either direction
111
Properties of a Doubly
Linked
List
In a doubly linked
list, the prior pointer of the first node will be
null, as there is no node before the first node.
In a doubly linked list, the next pointer of the last node will be
112
Declaration of a Doubly
Linkedstruct
List
marks_list
{
struct double_list *prior;
int info;
struct marks_list *next;
}
113
100
100
null
prior
120
1
marks
140
120
100
next
prior
marks
140
120
next
prior
marks
null
next
114
115
116
case 1 : addnode( );
break;
case 2 : deletenode( )
break;
case 3 : forward_traverse( );
break;
case 4 : reverse_traverse( );
break;
case 5: exit( );
break;
} /* end of switch */
} /* end of main( ) */
117
119
120
121
123
Searching a Value in a
Doubly Linked List
struct marks_list *search( int val)
{
for( ptr = start; (ptr); ptr = ptr->next)
{
if (val = = ptr-> marks)
return ptr;
}
struct marks_list *search( int val)
{
for( ptr = last; (ptr); ptr = ptr->prior)
{
if (val = = ptr-> marks)
return ptr;
}
124
125
if (ptr->next = = null)
{
temp = ptr;
prev->next = null;
last = ptr->prior;
}
}
}
126
Traversal of a Doubly
Linked List
/* forward traversal of a doubly linked list */
for( ptr = start; (ptr); ptr = ptr->next)
{
printf(%d, ptr->marks);
}
/* reverse traversal of a doubly linked list */
for( ptr = last; (ptr); ptr = ptr->prior)
{
printf(%d, ptr->marks);
}
127
Summary
In this session, you learnt to:
Describe the need for, and advantages of a
128
Binary Trees
129
Objectives
At the end of this lesson, you will be able to:
Define a binary tree
Describe the terminologies associated with a binary
tree
Use a dynamically allocated data structure to
represent a binary tree
Traverse, Add and delete nodes from a binary tree
Understand the Huffman Algorithm
Describe the types of Trees
130
Trees
Compared to linked lists that are linear data structures,
node.
In a tree structure, however, each node may point to several
131
Trees
Rajeev
Ravi
Ramesh
Vijay
Suresh
Anjali
Sukesh
Arvind
132
Trees
A tree consists of a collection of nodes that are
133
Trees
The root is the only node in the tree that does not have a
parent.
All other nodes in the tree have exactly one parent.
There are nodes in the tree that do not have any
134
Trees
A node is an ancestor of another node if it is the parent of
You may note that all the nodes in the tree are
135
Tree
An important feature of a tree is that there is a single
The length of the longest path from the root to any node
The root is at level 0 and the level of any node in the tree
Binary Tree
If you can introduce a restriction that each node can
137
Binary Tree
A complete binary tree can be defined as one whose non-leaf
nodes have non-empty left and right subtrees and all leaves
are at the same level.
This is also called as a balanced binary tree.
If a binary tree has the property that all elements in the left
138
139
140
141
142
subtrees.
143
RLR Preorder
LRR Postorder
LRR Inorder
144
145
147
Preorder Traversal
When we traverse the tree in preorder, the root node is
148
Preorder Traversal
Then, we traverse the left and right subtrees of C
Inorder Traversal
For inorder traversal, we begin with the left subtree
150
Inorder Traversal
Again, first its left subtree containing only one node D
Postorder Traversal
For postorder traversal, we must traverse both the left and
values D, E, C and B.
in DECBA.
152
153
154
155
The same rule applies to all the subtrees until they have
10
158
Root
10
15
159
Root
15
12
160
15
12
161
10
15
12
15
12
18
162
10
10
15
12
15
18
12
18
20
163
To find the insertion place for the new value, say 17, we
164
165
Root
15
12
18
20
166
167
10
Root
15
12
18
null
20
168
node (the node with value 18) to which you must link the
new node (node with value 17).
Once you know the insertion place, you must adjust the
170
171
172
Into
Treefor insertion into a binary tree takes
The Cafunction
two parameters; one is the pointer to the root node
(root), and the other is the value to be inserted (x).
173
175
You have
seen thatUsing
to insert a node,
you must compare x
Into
a Tree
Recursion
with root->info.
compare the new value (x) with the one in the root and
you use exactly the same insertion method either on the
left subtree or on the right subtree.
177
recursively as follows:
tree rinsert (s,x)
tree *s;
int x;
{
/* insertion into an empty tree; a special case of insertion */
if (!s)
{
s=(struct tree*) malloc (sizeof(struct tree));
178
180
Root
15
12
18
20
181
182
7
8
10
12
15
18
20
183
18
15
12
10
8
7
6
185
different cases.
186
187
p
1
null
188
simply make the link of the parent to nil as you did in the
case of a leaf node.
Because if you do so, you will lose all of the descendants
Node to be deleted
Node to be deleted
190
two children.
There is no way you can make the parent of the deleted
191
Therefore, you must attach the left subtree as far to the left
Delete node x
q
t
y
t
z
s
u
After Deletion of Node x
193
free(temp);
}
else if (p->right
== null)
{
temp = p;
p = p->left;
free (temp);
}
194
}
195
for
I, II
IIIwhen it finds a node with
NoteCases
that the while
loop&
stops
an empty left subtree so that the left subtree of the node
to be deleted can be attached here.
Also, note that you first attach the left subtree at the
196
p equal to p->right.
197
of the tree. You can write the code implementation for a tree search as follows:
search (p,x)
int x;
struct tree *p;
{
p = root;
while (p != null && p->info != x)
{
if (p->info > x)
p = p->left;
else
p = p->right;
} return (p);
}
198
GRAPHS
199
SEARCHING
Searching
Sequential Searches
Time is proportional to n
Binary search
Sorted array
Eliminative or a Binary
Search
The mode of accessing data in a linked list is linear.
Therefore, in the worst case scenario of the data in
linear.
202
Eliminative or a Binary
Search
A linear search is fine if the nodes to be searched in a
linked list are small in number.
But the linear search becomes ineffective as the
Eliminative or a Binary
Search
You will now be exposed to a game that will highlight
a new mechanism of searching.
NO
204
Eliminative or a Binary
Search
A coin is with one of the members in the audience
divided into the two sections on the left and the right
respectively as shown in the diagram.
The challenge facing X, the protagonist, is to find
205
Find position
c1 log2 n
Shuffle down
Overall
c2 n
c1 log2 n + c2 n
or
c2 n
Dominant
term
with R.
If X was to start the search with A and progress linearly
207
208
6 searches saved
X
NO
YES
211
Q
NO
R
YES
212
213
100
1 120
2 140
3 160
4 180
5 200
6 220
7 null
215
Search Value
Search Value
216
searching with the entire left subtree of the root node and
its descendant subtrees, in the process doing away with
searching one-half of the binary search tree.
Even while searching the right subtree of the root node and
218
Searching - Re-visited
Binary tree O(log n) if it stays balanced
Simple binary tree good for static collections
Low (preferably zero) frequency of
insertions/deletions
Its dynamic
Need to keep the tree balanced
Tree Traversal
Traversal = visiting every node of a tree
Three basic alternatives
Pre-order
Root
Left sub-tree
Right sub-tree
x A +x+BC xDE F
L
L R L
Tree Traversal
Traversal = visiting every node of a tree
Three basic alternatives
In-order
Left sub-tree
Root
11
Right sub-tree
A x B+C xDxE +F
L
L
R
Tree Traversal
Traversal = visiting every node of a tree
Three basic alternatives
Post-order
Left sub-tree
Right sub-tree
Root
11
A
L
B C + D E xx F+x
L
R
Tree Traversal
Post-order
Left sub-tree
Right sub-tree
Root
Reverse-Polish
11
(A (((BC+)(DEx) x) F +)x )
which traversal?
Trees -
Searching
In order:
AD E G H K L M N O PT V
Trees -
Searching
Trees -
Searching
Binary search tree
Trees -
Rotations
Binary search tree
Trees -
Rotations
Trees -
Red-Black Trees
A Red-Black Tree
Binary search tree
Each node is coloured red or black
Trees -
Red-Black Trees
A Red-Black Tree
Trees -
Red-Black Trees
A Red-Black Tree
Trees -
Red-Black Trees
A Red-Black Tree
Trees -
Red-Black Trees
A Red-Black Tree
Trees -
Red-Black Trees
Lemma
A RB-Tree with n nodes has
height 2 log(n+1)
Essentially,
Trees -
Red-Black Trees
Data structure
struct t_red_black_node {
enum { red, black } colour;
void *item;
struct t_red_black_node *left,
*right,
Same as a
*parent;
binary tree
}
Trees -
Insertion
Trees -
Insertion
if ( x->parent == x->parent->parent->left ) {
/* If x's parent is a left, y is x's right 'uncle' */
y = x->parent->parent->right;
we havent
reached the root
y->colour == red ) {
and if
xs(parent
is red
/* case 1 - change the colours */
x->parent->colour = black;
y->colour = black;
x->parent
x->parent->parent->colour
= red;
/* Move x up the tree */
x = x->parent->parent;
Trees -
Insertion
Trees -
Insertion
y is xs
/* right
case uncle
1 - change
right uncle
Trees -
Insertion
If the uncle
x->parent->parent
the colours of y, the grand-parent
and the parent
x->parent
right uncle
Trees -
Insertion
Trees -
Insertion
New x
Trees -
Insertion
if ( y->colour == red ) {
/* case 1 - change the colours */
x->parent->colour = black;
y->colour = black;
x->parent->parent->colour = red;
/* Move x up the tree */
x = x->parent->parent;
Trees -
Insertion
if ( y->colour == red ) {
/* case 1 - change the colours */
x->parent->colour = black;
y->colour = black;
x->parent->parent->colour = red;
/* Move x up the tree */
x = x->parent->parent;
.. So move x up and
rotate about x as root ...
else {
/* y is a black node */
if ( x == x->parent->right ) {
/* and x is to the right */
/* case 2 - move x up and rotate */
x = x->parent;
left_rotate( T, x );
Trees -
Insertion
if ( y->colour == red ) {
/* case 1 - change the colours */
x->parent->colour = black;
y->colour = black;
x->parent->parent->colour = red;
/* Move x up the tree */
x = x->parent->parent;
else {
/* y is a black node */
if ( x == x->parent->right ) {
/* and x is to the right */
/* case 2 - move x up and rotate */
x = x->parent;
left_rotate( T, x );
Trees -
Insertion
if ( y->colour == red ) {
/* case 1 - change the colours */
x->parent->colour = black;
y->colour = black;
x->parent->parent->colour = red;
/* Move x up the tree */
x = x->parent->parent;
else {
/* y is a black node */
if ( x == x->parent->right ) {
/* and x is to the right */
.. but
is still red
/* case 2 - move
x xs
up parent
and rotate
*/ ...
x = x->parent;
left_rotate( T, x );
Trees -
Insertion
else {
/* y is a black node */
if ( x == x->parent->right ) {
/* and x is to the right */
/* case 2 - move x up and rotate */
x = x->parent;
left_rotate( T, x );
uncle
Trees -
Insertion
else { /* case 3 */
x->parent->colour = black;
x->parent->parent->colour = red;
right_rotate( T, x->parent->parent );
}
Trees -
Insertion
.. Change colours
and rotate ..
else { /* case 3 */
x->parent->colour = black;
x->parent->parent->colour = red;
right_rotate( T, x->parent->parent );
}
Trees -
Insertion
else { /* case 3 */
x->parent->colour = black;
x->parent->parent->colour = red;
right_rotate( T, x->parent->parent );
}
Trees -
Insertion
else { /* case 3 */
x->parent->colour = black;
x->parent->parent->colour = red;
right_rotate( T, x->parent->parent );
}
Trees -
Insertion
else { /* case 3 */
x->parent->colour = black;
x->parent->parent->colour = red;
right_rotate( T, x->parent->parent );
}
}
else ....
Red-black trees -
Analysis
Addition
Insertion
Fix-up
Comparisons
At every stage,
x moves up the tree
at least one level
Overall
O(log n)
O(log n)
O(log n)
Deletion
Also
O(log n)
More complex
... but gives O(log n) behaviour in dynamic cases
know?
Code?
Its complexity
Basically how it works
Where to find an implementation