Sie sind auf Seite 1von 83

Data Structures

B.Navakumari November 9, 2011

0.1

Syllabus

141301 DATA STRUCTURES UNIT I LINEAR STRUCTURES Abstract Data Types(ADT)-List ADT-array based implementation-lined list implementation-cursor based linked lists-doubly linked lists-applications of lists-Stack ADT-Queue ADT-circular queue implementationApplications of stack and queues. UNIT II TREE STRUCTURES Tree ADT-Tree traversals-Left child right sibiling data structures for general trees- Binary tree ADT- expression trees-applications of trees-binary search tree ADT-Threaded BinaryTree. UNIT III BALANCED TREES AVL Trees-Splay Trees-B-Tree-heaps-binary heaps-applications of binary heaps. UNIT IV HASHING AND SET Hashing-Separate Chaining -open Addressing- Rehashing- Extendible Hashing-Disjoint SetADT- dynamic equivalence problem-smart union algorithms- path compression-application of Set. UNIT V GRAPHS Denitions-Topological Sort-Breadth-First Traversal-Shortest Path algorithms-minimum spanning tree-Prims and Kruskals algorithms-Depth First traversal-biconnectivity-Euler Circuits-Applications of graph. TOTAL : 45 TEXT BOOK 1. M.A.Weiss, Data Structures and Algorithm Analysis in C , Second Edition, Pearson Educatioon, 2005. REFERENCES: 1. A.V.Aho, J.E.Hopcroft and J.D.Ullman, Data Structures and Algorithms , Pearson Education , First Edition Reprint 2003. 2. R.F.Gilberg, B.A. Forouzan, Data Structures , Second Edition, Thomson India Edition,2005.

Contents
0.1 Syllabus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 7 7 7 8 8 8 9 9 9 11 12 13 13 16 16 17 20 20 21 21 22 23 25 28 29 30 32 32 32 35 35 35 35 36 37 37 37 40 41 42

1 LINEAR STRUCTURES 1.1 DATA STRUCTURES . . . . . . . . . . . . . . . . . . . . 1.1.1 Introduction: . . . . . . . . . . . . . . . . . . . . . 1.2 ABSTRACT DATA TYPES(ADT) . . . . . . . . . . . . . 1.2.1 Denition Of ADT: . . . . . . . . . . . . . . . . . 1.2.2 Operations Of ADT: . . . . . . . . . . . . . . . . . 1.2.3 Adavantages: . . . . . . . . . . . . . . . . . . . . . 1.3 LIST ADT . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3.1 Basic Operations Of List ADT . . . . . . . . . . . 1.4 ARRAY BASED IMPLEMENTATION . . . . . . . . . . 1.4.1 Basic Operations: . . . . . . . . . . . . . . . . . . . 1.5 LINKED LIST IMPLEMENTATION . . . . . . . . . . . . 1.5.1 Basic operations: . . . . . . . . . . . . . . . . . . . 1.6 CURSOR BASED LINKED LISTS . . . . . . . . . . . . . 1.7 DOUBLY LINKED LISTS . . . . . . . . . . . . . . . . . . 1.7.1 Basic Operations Of Doubly Linked Lists: . . . . . 1.8 APPLICATIONS OF LISTS . . . . . . . . . . . . . . . . 1.8.1 Polynomial Manipulation . . . . . . . . . . . . . . 1.9 STACK ADT . . . . . . . . . . . . . . . . . . . . . . . . . 1.9.1 Basic Operations Of Stack ADT: . . . . . . . . . . 1.9.2 Array Implementation of the Stack ADT: . . . . . 1.9.3 Implementation Of Stack ADT using Linked Lists: 1.9.4 Applications Of Stack ADT: . . . . . . . . . . . . 1.10 QUEUE ADT . . . . . . . . . . . . . . . . . . . . . . . . . 1.10.1 Basic Operations Of Queue ADT: . . . . . . . . . 1.10.2 Representation Of Linear Queue Using Array: . . . 1.10.3 Linked List Implementation Of Queue . . . . . . . 1.11 CIRCULAR QUEUE IMPLEMENTATION . . . . . . . . 1.12 APPLICATIONS OF QUEUE ADT . . . . . . . . . . . . 2 UNIT-II 2.1 TREE STRUCTURES . . . . 2.2 TREE ADT . . . . . . . . . . 2.2.1 Basic Terminologies: . 2.3 TREE TRAVERSALS . . . . 2.3.1 Preorder Traversal . . 2.3.2 Inorder Traversal . . . 2.3.3 Postorder Traversal . 2.3.4 BINARY TREE ADT 2.4 EXPRESSION TREES . . . 2.5 APPLICATIONS OF TREES

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . . 3

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

4 2.6 BINARY SEARCH TREE ADT . . . . . . . . . . 2.6.1 Basic Operations: . . . . . . . . . . . . . . . 2.6.2 Deletion: . . . . . . . . . . . . . . . . . . . THREADED BINARY TREES . . . . . . . . . . . 2.7.1 Basic Operations In Threaded Binary Tree: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

CONTENTS . . . . . . . . . . . . . . . . . . . . . . . . . 42 43 45 48 49 53 53 54 54 55 56 57 57 60 61 62 63 64 66 66 66 68 68 79 82 82

2.7

3 UNIT-III 3.1 HEIGHT BALANCED TREES ( AVL TREES ) 3.1.1 Left-of-Left Rotation: . . . . . . . . . . . 3.1.2 Right-of-Right Rotation: . . . . . . . . . . 3.1.3 Right-of-Left Rotation: . . . . . . . . . . 3.1.4 Left-of-Right: . . . . . . . . . . . . . . . . 3.2 SPLAY TREES . . . . . . . . . . . . . . . . . . . 3.2.1 Splaying: . . . . . . . . . . . . . . . . . . 3.3 B-TREE . . . . . . . . . . . . . . . . . . . . . . . 3.3.1 B - Tree: . . . . . . . . . . . . . . . . . . 3.3.2 Search Operation in a B-Tree: . . . . . . . 3.3.3 Insert Operation in a B-Tree: . . . . . . . 3.3.4 Delete Operation in B-Tree: . . . . . . . . 3.4 HEAPS . . . . . . . . . . . . . . . . . . . . . . . 3.4.1 Denition Of Heaps . . . . . . . . . . . . 3.4.2 Basic Operations Of Heaps . . . . . . . . 3.5 UNIT-V . . . . . . . . . . . . . . . . . . . . . . . 3.5.1 BASIC TERMINOLOGIES IN GRAPH: 3.6 MINIMUM SPANNING TREE . . . . . . . . . . 3.7 Depth First Traversal . . . . . . . . . . . . . . . 3.8 BI CONNECTIVITY . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

List of Figures
1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12 2.13 2.14 2.15 2.16 2.17 2.18 2.19 2.20 3.1 3.2 3.3 3.4 3.5 3.6 3.7 Various Types Of Data Structures . . . . . . . . . . Representation Of Node . . . . . . . . . . . . . . . . Representation Of Doubly Linked list . . . . . . . . Representation Of Circularly Linked List . . . . . . Representation Of a Polynomial Node . . . . . . . . Representation Of Push Operation . . . . . . . . . . Representation Of Pop Operation . . . . . . . . . . . Representation Of Push in Stack Using Linked Lists Representation Of Pop in Stack Using Linked List . Representation Of a Queue . . . . . . . . . . . . . . Representation Of Circular Queue . . . . . . . . . . Representation Of a Queue . . . . . . . . . . . . . . Queue . . . . . . . . . . . . . . . . . . . . . . . . . . Structure Of Tree . . . . . . . . . . . . Tree Traversal . . . . . . . . . . . . . . Tree Traversal . . . . . . . . . . . . . . Tree Traversal . . . . . . . . . . . . . . Types Of Tree . . . . . . . . . . . . . Array Representation Of Binary Tree . Linked Representation Of Binary Tree Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Binary Search Tree . . . . . . . . . . . Threaded Binary Tree . . . . . . . . . AVL Trees . . . . . . . . Left Of Left Rotation . Right Of Right Rotation Right Of Left Rotation . Left Of Right Rotation . Zig Operation . . . . . . Zig Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 10 11 11 21 22 23 24 24 28 30 30 31 36 38 39 40 41 42 42 43 44 44 45 45 46 46 47 47 48 48 49 49 53 54 55 56 57 58 58

6 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17 3.18 3.19 3.20 3.21 3.22 3.23 3.24 3.25 3.26 3.27 3.28 3.29 3.30 3.31 3.32 3.33 3.34 3.35 3.36 3.37 3.38 3.39 3.40 3.41 3.42 3.43 3.44 3.45 3.46 3.47 3.48 3.49 3.50 3.51 3.52 3.53 Zig-zig Operation . . . . . . . Zig-zig Operation . . . . . . . Zig-zag Operation . . . . . . Zig-zag Operation . . . . . . B-Tree . . . . . . . . . . . . . B-Tree . . . . . . . . . . . . . Searching in B-Tree . . . . . Insertion Operation in B-Tree Insertion in B-Tree . . . . . . Deletion in B-Tree . . . . . . Deletion in B-Tree . . . . . . Deletion in B-Tree . . . . . . Heap . . . . . . . . . . . . . . Heap . . . . . . . . . . . . . . Deletion in Heap . . . . . . . Directed Graph . . . . . . . . Undirected Graph . . . . . . Loop Path . . . . . . . . . . . Cycle Graph . . . . . . . . . Connected Graph . . . . . . . Strongly Connected Graph . Weakly Connected Graph . . Directed Graph(or) Digraph . Undirected Graph . . . . . . Cycle . . . . . . . . . . . . . . Loop . . . . . . . . . . . . . . Disjoint . . . . . . . . . . . . Degree Of the Graph . . . . . Degree Of the Graph . . . . . Degree Of the Graph . . . . . Breadth First Traversal . . . Breadth First Traversal . . . Single Source Shortest Path . Single Source Shortest Path . Single Source Shortest Path . Single Source Shortest Path . Single Source Shortest Path . Single Source Shortest Path . Single Source Shortest Path . Undirected Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Depth First Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

LIST OF FIGURES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 59 60 60 61 61 62 63 63 64 64 65 66 66 67 68 68 69 69 69 70 70 70 71 71 71 72 72 73 73 76 76 77 77 77 78 78 78 79 79 80 80 80 81 81 82

Chapter 1

LINEAR STRUCTURES
1.1
1.1.1

DATA STRUCTURES
Introduction:

A Data Structure is a data object together with the relationships that exist among the instances and among the individual elements that compose an instance. In other words, A data structure denes a way of organizing all data items that consider not only the item stored but also stores the relationship between the elements. A data structure represents the logical relationship that exists between the individual elements of data to carry out certain tasks. A data structure is an actual implementation of an array. A data structure is a physical representation of an ADT. It indicates the data type and also suggest how these could be stored on the computer memory. For example, an integer as a data structure can be dened

Figure 1.1: Various Types Of Data Structures as a integer data type stored on consecutive memory bytes. An abstract data type(ADT) is a data type in which the members of the data type are unknown to users of the type. 7

CHAPTER 1. LINEAR STRUCTURES

Abstraction refers to dene new types, hiding the details of implementation. The following diagram shows the classication of data structures. Primary data structures are the basic data structure that directly operate upon the machine instruction. They have dierent representation on dierent computers. All the basic constants(integer, oating point numbers, character constant, string constant) and pointers are considered as primary data structures. They emphasize on grouping same (or) dierent data items with relationship between each data item. Compound data structure can be broadly classied into two types such as static and dynamic data structures. If a data structure is created using the static memory allocation (data structure formed when the no of data items are known in advance)it is known as static data structure(or) xed size data structure. Example: Arrays, Structures. If a data structure is created using the dynamic memory allocation (data structure formed when the no of data items are not known in advance)it is known as dynamic data structure(or) variable size data structure. Dynamic data structure can be classied into two types such as linear and non-linear data structures.

Linear Data Structure: Linear data structures have the linear relationship between its adjacent elements. Example: Liinked Lists. A linked lists is a dynamic data structure that can grow and shrink during its execution time.

Non-Linear Data Structures Non-linear data structure dont have a linear relationship between its adjacent elements. Each node may point to several nodes. But in linear data structure ,each node has a link which points to another node. Example: Tree, Graph. A tree is a non-linear data structure that may point to one(or)more nodes at a time. A graph is similar to tree except that it has no relationship between its adjacent elements.

1.2
1.2.1

ABSTRACT DATA TYPES(ADT)


Denition Of ADT:

Abstract data type is a setup operation, which are mathematical abstraction. An ADT denition is their any mention of how the set of operation is implemented. These operations are along with their objects such as list, sets and graphs can be viewed as a ADT. The ADT data types are integers real and Boolean variables. A data type that is dened entirely by a set of operations is referred to as an ADT. These operations provide a representation independent specication. An ADT is a combination of interface and implementation. The interface denes the logical properties of an ADT and especially the signature of its operation. The implementation denes the representation of the data structure and the algorithms that implement the operations.

1.2.2

Operations Of ADT:

Creation

1.3. LIST ADT Insertion Deletion Copy Modify

1.2.3

Adavantages:

1. It is very much easier to debugging the small routines to larger routines. 2. It is very much easier for several peoples to work on a modular program simultaneously. 3. It is easy to modify and change the programs and large routines.

1.3

LIST ADT

Linear List: A Linear list is a data object whose instances are of the form ( e1, e2, en), where n is a nite natural number. ei Element of the list. n length of the list. s size of the element. For example, a list of names, list of marks, etc.

1.3.1

Basic Operations Of List ADT

The following operations that are performed on a linear list are, 1. Create a list. 2. Delete a list. 3. Determine whether the list is empty. 4. Determine the length of the list. 5. Find the kth element. 6. Search for a given element. 7. Delete the kth element 8. Insert a new element. 9. Display all elements. Linked Lists: A list is a collection of elements are arranged in a linear sequence. A list with size zero / with no elements is referred to as empty list. Linked list is a linear data structure used to implement dynamic allocation. A common example for static allocation is arrays. Linked list is a dynamic data structure as their size can grow(or) shrink during its execution. The nodes can be added anytime to the list (or) deleted from the list. Each element in the linked list(or)List is referred as a node. Each node contains two elds. Data eld Link Field The data eld contains the actual data of the element to be stored in the list.

10

CHAPTER 1. LINEAR STRUCTURES

Figure 1.2: Representation Of Node The link eld also referred as next address eld contains the address of the next node in the list. A linked list contains a pointer referred as the head pointer which points to the rst node in the list, that stores the address of the rst node in the list. The address stored in a linked list are divided into three types namely, External Address Internal Address Null Address External Address is the address of the rst node in the list. This address is stored in the head pointer which points to the rst node in the list.The entire linked list can be accessed only with the help of the head pointer. Internal address is the address stored in each and every node of the linked list except the last node. The content stored in the link eld is the address of the next node. Null address is the address stored by the NULL pointer of the last node of the list which indicates the end of the list. Types Of Linked Lists: The dierent types of Linked lists are, 1. Singly linked list. 2. Doubly linked list 3. Circularly linked list Singly Linked Lists: Each node has a single link to its next node. Also referred as a linear linked lists. The head pointer points to the rst node in the list and null pointer is stored in the link eld of the last node in the list which indicates the end of the list. In SLL, we can traverse in only one direction(from head to null in the list) Doubly Linked Lists: For some applications, we can traverse in both directions. Doubly Linked Lists work much better than singly liked lists. In doubly linked list each node contains three elds namely, Previous Address Field Data Field Next Address Field. The This The The Previous address eld of a node contains address of its previous node. eld is also referred as the backward link eld. data eld stores the information part of the node. next address eld contains the address of the next node in the list. This eld is also referred as the

1.4. ARRAY BASED IMPLEMENTATION

11

Figure 1.3: Representation Of Doubly Linked list forward link eld.

Circularly Linked Lists: Circular linked list is a linked list in which the last node of the list is connected to the rst node in the list. They are dierent types of circular linked list.They are, Circular Singly Linked List. Circular Doubly Linked List. Circular linked list looks like a cyclic list where their wont be any end of the list.

Figure 1.4: Representation Of Circularly Linked List Implementation Of List ADT: The lineaer list can be implemented in two ways. Array Implementation Of List Linked List Implementation Of List.

1.4

ARRAY BASED IMPLEMENTATION

Array implementation of the mainly used to print the list of elements in it and to nd the specic element in the list. These two operations take place in a linear running time, where as the running time for insertion and deletion operation. Both list and array are ordered collection of elements , but these are dierent. The no of elements in the array is xed and it is not possible to change the no of elements. But, the size of the list varies continuously when elements are inserted (or) deleted. The list is stored in a part of the array,so that the array can be declared large enough to hold the max no of elements of the list. During execution of the program, the size of the list can be varied with in the space reserved for it. One end of the array is xed, and the other end of the array is constantly changed depending upon the elements inserted (or) deleted in the list.

12

CHAPTER 1. LINEAR STRUCTURES

1.4.1

Basic Operations:

The following operations that can be performed on a singly linked list are, Creation Of List Insertion Of Node. Deletion Of Node. Modication Of a Node Traversal Of a list Search x in the list. Find the length of the list. Display all the elements of the list. Traversal Of a List: Visit all nodes exactly once in a linear list. Algorithm: Algorithm TraversalSLL(Head) Begin Temp Head while(Next(Temp)!=null) Temp Next(Temp) end while end. Length Of the List: This operation is used to count all nodes in the list. Algorithm: Algorithm LengthSLL(Head) Begin count 0 Temp Head while(Temp!=null) Temp Next(Temp) count count+1 end while Write count End. Searching of an element in SLL: To search a particular element from the linear list. Algorithm: Algorithm SearchSLL(Head,X) Begin Temp Head while(Temp!=null) if(Data(Temp)=x)then Write x is present

1.5. LINKED LIST IMPLEMENTATION Quit else Temp Next(Temp) end while Write x is not present End.

13

1.5

LINKED LIST IMPLEMENTATION

The list can be implemented by using pointers.

1.5.1

Basic operations:

The basic operations can be performed on the singly linked list are, Creation Of List Insertion Of Node. Deletion Of Node. Modication Of a Node Traversal Of a list Search x in the list. Find the length of the list. Display all the elements of the list. Creation Of a List: Creating a node. Reading details for a node from the user. Connect the node with the list. Algorithm: Algorithm CreateList() Begin Set Newnode=GetNode() Call Readnode(Newnode) Set Head=Newnode Set Last=Newnode If we want to add another node proceed else stop the process. Set Newnode=Getnode() Call Readnode(Newnode) Assign Last Link=Newnode Assign Last=Last Link Goto step5 End. Insertion Of a Node: The new node can be inserted in the list at three dierent places. Inserting as a rst node in the list.

14 Inserting as a last node in the list. Inserting as an intermediate node in the list. Insertion At First Position: Algorithm InsertFirst(Head) Begin Set Newnode=Getnode() Call Readnode(Newnode) if(Head==NULL) Set Head=Newnode Assign Newnode Link=Head Set Head=Newnode End. Insertion At Last Position: Algorithm InsertLast(Head) Begin Set Newnode=Getnode() Call Readnode(Newnode) if(Head==NULL) Set Head=Newnode Set Last=Head Repeat while(Last Link!=NULL) Assign Last=Last Link Assign Last Link=Newnode End. Insertion At Middle Position:

CHAPTER 1. LINEAR STRUCTURES

Algorithm InsertMiddle(Head,last,newnode) Begin Set Newnode=Getnode() Call Readnode(Newnode) if(Head==NULL) Set Head=Newnode Write Enter the data of the node after which the insertion is to be made: Read condition Set last=head Repeat while(last!=NULL) if(last data==condition)then Assign Newnode Link= last link Assign last link=newnode else Assign last=last link Write Condition is not available End. Deletion Of a Node: Another primitive operation that can be done on the singly linked list is the deletion of a node. Memory is to be released for the node to be deleted. A node can be deleted from the list from three dierent places namely, Deleting the rst node from the list. Deleting the last node from the list.

1.5. LINKED LIST IMPLEMENTATION Deleting an intermediate node from the list. Deletion at rst position: Algorithm DeleteFirst() Begin if(Head==NULL) Write List is empty; Set Delnode=Head Assign Head=Head link Write Deleted data is,Delnode data Call Releasenode(Delnode); End. Deletion at last position: Algorithm DeleteLast(Head) Begin if(Head==NULL) Write List is empty; if(Head link==NULL)then Set Delnode=Head Set Head=NULL PrintDeleted Data is,Delnode data Set last=Head Repeat while(last link!=NULL) Assign Prev=last Assign last=last link Set Delnode=last Prev link=NULL PrintDeleted data is,Delnode data; Call Releasenode(Delnode); End. Display the Contents Of the List: Algorithm ViewList() Begin if(Head==NULL) Write List empty while(Head!=NULL) WriteThe data is, Head data Head=Head link End. Count the elements in the list: Algorithm Countlist() Begin Set Count=0 if(Head==NULL) Write List is empty while(Head!=NULL) Count=Count+1 Head=Head link Return Count End.

15

16

CHAPTER 1. LINEAR STRUCTURES

1.6

CURSOR BASED LINKED LISTS

Suppose we dont have pointer in C.If we want to still implement linked list in C, create an array of structures,which contains collection of nodes. Each array of structures holds a data element and a link(an integer value) which acts as the pointer to the next element . The content to be stored in the next link is the index of the next node. The advantage of using linked list is to dynamically allocate the memory for the nodes when needed. This is achieved in this case using array of structures, but since the size of the array of structures is xed,this type of lists is referred to as static linked lists also referred to as cursor implementation of linked lists. Since the index values of array structures are used in implementation of static linked list accessing is fast compared to pointer in dynamic linked list. Cursor in the implementation of static linked list means an integer, which indicates the index position in the array. In the cursor list every node consists of two elds such as data eld and link eld. The link eld is the one which points to the next node. The content to be stored in the link eld is the index of the next node. The array of structures has to be initialized before storing the data, by assigning the link value of each node by the index of the immediate next node. In the cursor list array, the node with the index 0 is used as the header. The value 0 in the link eld indicates the end of the list(similar to NULL in a dynamic linked lists). Cursor allocation in Static Linked List: Steps to be followed to allocate a cursor. Too store data for the data eld,memory has to be allocated which is always started from the rst node of the cursor list. Get the free node from the link of the rst node of the cursor list. Assign the link of the new node to the link of the rst node. Assign the link of the new node to zero. The next free node is found from the link of the rst node of the cursor list. Cursor Deallocation in Static linked Lists: Steps to be followed to deallocate a cursor in a static linked lists To remove a node from the list, memory has to be deallocated. Assign the link of the removed node with the link of the rst node. Assign the link of the rst node with the index of the node to be removed.

1.7

DOUBLY LINKED LISTS

Doubly Linked Lists: The Doubly linked list is a collection of nodes each of which consists of three parts namely the data part, prev pointer and the next pointer. The data part stores the value of the element, the prev pointer has the address of the previous node and the next pointer has the value of the next node. In a doubly linked list, the head always points to the rst node. The prev pointer of the rst node points to NULL and the next pointer of the last node points to NULL.

1.7. DOUBLY LINKED LISTS

17

1.7.1

Basic Operations Of Doubly Linked Lists:

The following operations that can be performed on a Doubly linked list are, 1. Creation Of a list. 2. Insertion of a node. 3. Modication of a node. 4. Deletion of a node. 5. Traversal of a list. 6. Count the number of elements. 7. Display all the elements of the list. Creation Of Lists: The creation of list involves three processes. They are Creating a node Reading details for a node from the user. Connect the node with the list. Algorithm: Algorithm CreateList() Begin Set Newnode=GetNode() Call Readnode(Newnode) Set Head=Newnode Set Last=Newnode If we want to add another node proceed else stop the process. Set Newnode=Getnode() Call Readnode(Newnode) Assign Last FLink = Newnode Assign Newnode BLink=Last Assign Last=Last FLink Goto step5 End. Insertion Of a Node: The new node can be inserted in the list at three dierent places. Inserting as a rst node in the list. Inserting as a last node in the list. Inserting as an intermediate node in the list. Insertion At First Position: Algorithm InsertFirst(Head) Begin Set Newnode=Getnode() Call Readnode(Newnode) if(Head==NULL) Set Head=Newnode

18 Assign Newnode FLink=Head Assign Head BLink= Newnode Set Head=Newnode End. Insertion At Last Position: Algorithm InsertLast(Head) Begin Set Newnode=Getnode() Call Readnode(Newnode) if(Head==NULL) Set Head=Newnode Set Last=Head Repeat while(Last FLink NULL) Assign Last=Last FLink Assign Last FLink=Newnode Assign Newnode BLink=Last End. Insertion At Middle Position:

CHAPTER 1. LINEAR STRUCTURES

Algorithm InsertMiddle(Head,last,newnode) Begin Set Newnode=Getnode() Call Readnode(Newnode) if(Head==NULL) Set Head=Newnode Write Enter the data of the node after which the insertion is to be made: Read condition Set last=head Repeat while(last NULL) if(last data==condition)then Assign Next= last Flink Assign Newnode FLink=Next Assign Newnode BLink = last Assign last FLink=Newnode if(Next NULL) Assign Next BLink=Newnode else Assign last=last-Flink Write Condition is not available End. Deletion Of a Node: Another primitive operation that can be done on the singly linked list is the deletion of a node. Memory is to be released for the node to be deleted. A node can be deleted from the list from three dierent places namely, Deleting the rst node from the list. Deleting the last node from the list. Deleting an intermediate node from the list. Deletion at rst position: Algorithm DeleteFirst()

1.7. DOUBLY LINKED LISTS Begin if(Head==NULL) Write List is empty; Set Delnode=Head Assign Head=Head FLink if(Head NULL) Assign Head BLink=NULL Write Deleted data is,Delnode-data Call Releasenode(Delnode); End. Deletion at last position: Algorithm DeleteLast(Head) Begin if(Head==NULL) Write List is empty; if(Head FLink==NULL)then Set Delnode=Head Print Deleted data is, Delnode data Set Last=Head Repeat while(Last FLink NULL) Assign Last=Last FLink Set Delnode=Last Assign Last BLink FLink=NULL PrintDeleted Data is,Delnode-data Call Releasenode(Delnode); End. Deletion At Middle Position: Algorithm DeleteMiddle() if(Head==NULL) Print List empty Print Enter the data of any node in the list for delete Read deldata if(Head data=deldata) then Set Delnode=Head Assign Head=Head FLink if(Head NULL) Assign Head BLink=NULL PrintDeleted data is, Delnode data Call Releasenode(Delnode) Set Last=Head FLink Repeat while(Last NULL) if(Last data==deldata) then Set Delnode=Last Set Prev=Last BLink Set Next=Last FLink Assign Prev FLink=Next if(Next NULL) Assign Next BLink=Prev Print The Deleted data is Delnode data Call Releasenode(Delnode) else Assign Last=Last FLink Print Deldata is not avaialble in the list

19

20 End. Display the Contents Of the List: Algorithm ViewList() Begin if(Head==NULL) Write List empty while(Head NULL) WriteThe data is, Head data Head=Head FLink End. Count the elements in the list: Algorithm Countlist() Begin Set Count=0 if(Head==NULL) Write List is empty while(Head NULL) Count=Count+1 Head=Head FLink Return Count End.

CHAPTER 1. LINEAR STRUCTURES

1.8

APPLICATIONS OF LISTS

Linked lists form the basis of many data structures. Some important application using linked lists are, Polynomial Manipulation Stack Queue

1.8.1

Polynomial Manipulation

Linked list is generally used to represent and manipulate polynomials polynomials are expressions containing terms with non zero coecients and exponents. For example P(X)=a0x+a1x+........an-1x+an where, P(X) is a polynomial in X a0,a1,....an-1,an are constants and n is a positive integer. In the linked list representation of polynomials each term / element in the list is referred as a node. Each node contains three elds namely, Coecient Field Exponent Field Link Field

1.9. STACK ADT

21

Figure 1.5: Representation Of a Polynomial Node The coecient and exponent eld stores the data of a polynomial. The coecient eld holds the value of the coecient of a polynomial and the exponent eld holds the exponent value of the polynomial. The link eld contains the address of the next term in the polynomial. Creating a polynomial using a singly linked list starts with creating a node. Sucient memory has to be allocated for creating a node. The information is stored in the memory allocated by using malloc(). The getnode() is used for creating a node. After allocating memory for the structure of type poly the information for the terms(coef and expo) has to be read from the users. After, wee can do all the basic operations such as insertions and deletions in the polynomial lists.

1.9

STACK ADT

A stack is an ordered collection of items accessed as last-in-rst-out order. A stack is a list of elements in which insertions and deletions are restricted to one end. The end from which the elements are added/removed is referred to as top of the stack.Stack is also referred as piles and push down lists. The rst element placed in the stack will be at the top of the stack. The last element placed in the stack will be at the top of the stack. The last element added to stack is the rst element to be removed.Hence, the stacks are referred to as Last-in-rst-out lists. A stack is referenced via a pointer to the top elements of the stack referred as top pointer.The top pointer keeps track of the top element in the stack. Initially, when the stack is empty, the top pointer has a value zero and when the stack contains a singly element the top pointer has a value one and so on. Example: Bangles in a lady hand , Coaches of train, piles of notebook. Stacks: A stack is a data structure in which addition of new element or deletion of an existing element always takes place at the same end. This end is often known as top of stack. When an item is added to a stack, the operation is called push, and when an item is removed from the stack the operation is called pop. Stack is also called as Last-In-First-Out (LIFO) list.

1.9.1

Basic Operations Of Stack ADT:

The primitive operations of the stack include PUSH and POP. PUSH: Allows adding an element at the top of the stack. A push operation adds (or) inserts a new element to the stack. Each time a new element is inserted in the stack , the top pointer is incremented by one before the element is placed on the stack. The general syntax for inserting a new element into the stack. Push(S,X). The element x is inserted into the stack s . POP: Allows removing an element from the top of the stack. A pop operation deletes the top most element in the stack. Each time, an element is removed from the stack, the top pointer is decremented by one.

22

CHAPTER 1. LINEAR STRUCTURES

The general syntax for removing an element from the stack. Pop(S); Used to delete the top element from the stack. PEEK: Allows displaying top element of the stack. A peek is an operation used to display the element from the top of the stack, pointed by the top pointer. The general syntax is used to return the element at the top of the stack. Top(S). Implementation Of the Stack ADT: A stack can be implemented in two ways. Array Linked list

1.9.2

Array Implementation of the Stack ADT:

An array is a place holder to store the elements of the stack.The size of an array should be xed .An integer variable top can be used to mark the top of the stack.The notation top= -1 is used for initializing the top variable. Top can be made to point to the top element of the stack. When a new element is to be pushed then the top can be incremented and the element can be added.In this notation, top will be -1 for an empty stack. Push operation: If the elements are added continuously to the stack using the push operation then the stack grows at one end. Initially when the stack is empty the top = -1. The top is a variable which indicates the position of the topmost element in the stack.

Figure 1.6: Representation Of Push Operation

Algorithm: Push (S,N,Top,X) // S Name of the array. // N Size of the array. // X New element Begin If(Top=N-1) then Write Stack Overow Else Top Top +1

1.9. STACK ADT

23

S[Top] x End if End. Pop operation: On deletion of elements the stack shrinks at the same end, as the elements at the top get removed. Algorithm:

Figure 1.7: Representation Of Pop Operation

Pop(S,Top) Begin If(Top -1) Write Stack Underow Else X S[Top]; Top Top-1; End if End. If arrays are used for implementing the stacks, it would be very easy to manage the stacks. However, the problem with an array is that we are required to declare the size of the array before using it in a program. This means the size of the stack should be xed. We can declare the array with a maximum size large enough to manage a stack. As result, the stack can grow or shrink within the space reserved for it. The following program implements the stack using array.

1.9.3

Implementation Of Stack ADT using Linked Lists:

The stack can be implemented by using the singly linked list.This type of the representation has more advantage than representing stack using array. They are, It is not necessary to specify the no of elements to be stored in a stack during its declaration. (memory is allocated dynamically at run time when an element is added to the stack). Insertion and deletion can be handled easily and eciently. Linked list representation of stack can grow and shrink in size without wasting the memory space depending upon the insertion and deletion that occurs in the list. Initially, when the stack is empty, top points to NULL. When an element is added using the push operation, top is made to point to the latest element whichever is added.

24

CHAPTER 1. LINEAR STRUCTURES

Push operation: Create a temporary node and store the value of x in the data part of the node. Now make link part of temp point to Top and then top point to Temp. That will make the new node as the topmost element in the stack.

Figure 1.8: Representation Of Push in Stack Using Linked Lists

Algorithm: Push(Head,X) Begin Temp newnode Data(Temp) x Next(Temp) Head Head Temp End. Pop operation: The data in the topmost node of the stack is rst stored in a variable called item. Then a temporary pointer is created to point to top. The top is now safely moved to the next node below it in the stack. Temp node is deleted and the item is returned.

Figure 1.9: Representation Of Pop in Stack Using Linked List

Algorithm:

1.9. STACK ADT

25

Pop(Head,X) Begin Temp New node Data(Temp) x Next(Temp) NULL If(Head==NULL) then Head Temp Else Temp1 Head While(Next(Temp1)!=NULL) Temp1 Next(Temp1) Next(Temp1) Temp End if End. Note: The dierence between the stack and linked list is that insertion and deletion may occur anywhere in a linked list , but only at the top node in a stack.

1.9.4

Applications Of Stack ADT:

Some of the applications of the stack include, Towers of Hanoi Reversing the String Balanced Parenthesis Recursion using stack Evaluation of Arithmetic Expressions Towers of Hanoi: Towers of Hanoi is a gaming puzzle. Invented by French Mathematician Edouard Lucas in 1883. The objective of this puzzle is to transfer the entire disks from Tower3 using Tower2. The rules to be followed in moving the disks from tower1 to tower3 using tower2. Only one disc can be moved at a time. Only the top disc on any tower can be moved to any other tower. A larger disc cannot be placed on a smaller disc. It can be implemented using recursion. To move the largest disc to the bottom of tower3. We move the remaining n-1 disks to tower2 and then move the largest disc to tower 3. This process is continue until to place the entire disc in towerr3 in order. Since,disc are moved from each tower in a LIFO manner each tower may be considered as stack. The least no of moves required to solve the problem according to our algorithm is given by O(N)= 2N-1. The time complexity is measured in no of movements. Reversing the String: Main characteristics of the stack is reversing the order of its contents. The tasks can be accomplished by pushing each character until the end of the string. Now, the individual characters are popped o from the stack. Since the last character pushed into the stack would be the rst character to be popped o from the stack. The string will come o in the reverse order.

26

CHAPTER 1. LINEAR STRUCTURES

Since, the individual character are moved from the stack in a LIFO manner, the stack operation is implemented. For example, The input string is Kumar. The output string is ramuk. Recursion Using Stack: Recursion is a process by which a function calls itself repeatedly until some specied conditions has been satised. When a recursive program is executed, the recursive function calls are not executed immediately. They are placed on a stack (LIFO) until the condition that terminates the recursive function. The function calls are then executed in reverse order, as they are popped o the stack. For example, Main() Int num,fac; Printf(Enter the no); Scanf( Fac=fact(num); Printf(The factorial val Int fact(int x) If(x=1) Return 1; Else Return (x*fact(x-1)); Evaluation Of Arithmetic Expression: An expression consists of two components namely Operands and Operators. Operators indicate the operation to be performed. Operands are the variables and constants. There are three ways of representing expression in computers. They are, Inx Notation Prex Notation Postx Notation Inx Notation: The normal way of representing mathematical expression is called as inx expression. In this form of expressing an arithmetic expression the operator comes in between its operands. For example, (a+b). The operator + is written in between the operands a and b. Advantages: It is the mathematical way of representing the expression. Its easier to see visually which operation is done from the rst to last. Prex Notation: Also referred as polish notation. It is a way of representing algebraic expression without the use of parenthesis (or) rules of operator precedence. In this form of expressing an arithmetic expression the operator is written before its operands. For example, (+ab) The operator + is written after the operands a and b. Conversion Of Notation: Rules to be followed during inx to postx conversion. Fully,paranthesize the expression starting from the left to right(During paranthesizing the operators having

1.9. STACK ADT

27

higher precedence are rst paranthesized. Move the operators one by one to their right,such that each operator replaces their corresponding right paranthesis. The part of the expression, which has been converted into postx is to be treated as single operand. Once, the expression is converted into postx form remove all paranthesis. For example, the inx expression is, A+B Rules to be followed during inx to prex conversion: Fully paranthesize the expression starting from left to right. Move the operator one by one to their left such that each operator replaces their corresponding left paranthesis. The part of the expression which has been converted into prex is to be treated as single operand. Once the expression is converted into prex form remove all the paranthesis. Evaluation Of Expression: To evaluate an expression,assign the priority for the operators. The operators with the highest priority will be evaluated rst. The priority is listed in the order of highest to lowest. Priority Operation 1 Exponentation 2 Multiplication 3 Addition,Subtraction Converting Inx Expression To Postx Form Using Stack: The following procedure is used to convert inx to postx expression. Read the inx string Traverse from left to right of the expression. If an operand is encountered, add to the postx string. If the item is an operator push it on the stack, if any one of the following conditions are satised. The stack is empty If the precedence of the operator at the top of the stack is of lower priority than the operator being processed. When the inx string is empty,pop the elements of the stack on to the postx string to get the result. Evaluating An Postx Expression Using A Stack: Rules for evaluating a postx expression using stack. Traverse from the left to right of the expression. If an operand is encountered push it onto the stack. If an operator is encountered pop two elements from the stack evaluate those operands with that operator and push the result back in the stack. When the evaluation of the entire expression is over, the only thing left on the stack should be the nal result. If there are zero (or) more than one operands left on the stack either your program is inconsistent (or) the expression was invalid. Postx Notation: Also referred as sux notation (or) reverse polish notation. In this form of expressing an arithmetic expression the operator is written after its operands. For example, (ab+) Conversion of Inx Expression to Postx Expression The stacks are frequently used in evaluation of arithmetic expressions. An arithmetic expression consists of operands and operators. The operands can be numeric values or numeric variables. The operators used in an arithmetic expression represent the operations like addition, subtraction, multiplication, division and exponentiation. The arithmetic expression expressed in its normal form is said to be Inx notation, as shown: A + B The above expression in prex form would be represented as follows: + AB The same expression in

28

CHAPTER 1. LINEAR STRUCTURES

postx form would be represented as follows: AB + Hence the given expression in inx form is rst converted to postx form and then evaluated to get the results. The function to convert an expression from inx to postx consists following steps: 1. Every character of the expression string is scanned in a while loop until the end of the expression is reached. 2. Following steps are performed depending on the type of character scanned. (a) If the character scanned happens to be a space then that character is skipped. (b) If the character scanned is a digit or an alphabet, it is added to the target string pointed to by t. (c) If the character scanned is a closing parenthesis then it is added to the stack by calling push( ) function. (d) If the character scanned happens to be an operator, then rstly, the topmost element from the stack is retrieved. Through a while loop, the priorities of the character scanned and the character popped opr are compared. Then following steps are performed as per the precedence rule. i. If opr has higher or same priority as the character scanned, then opr is added to the target string. ii. If opr has lower precedence than the character scanned, then the loop is terminated. Opr is pushed back to the stack. Then, the character scanned is also added to the stack. (e) If the character scanned happens to be an opening parenthesis, then the operators present in the stack are retrieved through a loop. The loop continues till it does not encounter a closing parenthesis. The operators popped, are added to the target string pointed to by t. 3. Now the string pointed by t is the required postx expression. Evaluation of Expression entered in postx form: The program takes the input expression in postx form. This expression is scanned character by character. If the character scanned is an operand, then rst it is converted to a digit form and then it is pushed onto the stack. If the character scanned is a blank space, then it is skipped. If the character scanned is an operator, then the top two elements from the stack are retrieved. An arithmetic operation is performed between the two operands. The type of arithmetic operation depends on the operator scanned from the string s. The result is then pushed back onto the stack. These steps are repeated as long as the string s is not exhausted. Finally the value in the stack is the required result and is shown to the user.

1.10

QUEUE ADT

A queue is a linear data structure. A queue is an ordered collection of elements in which are accessed in a rst-in-rst-out(FIFO) order. In a queue, the elements which are inserted at one end and deletions are made at another end. The end at which the insertions are made is referred to as the rear end. The end at which the deletions are made is referred to as the front end. In a queue , the rst element inserted will be the rst element to be removed. So a queue is referred to as FIFO List.(First-in-First-out List).

Figure 1.10: Representation Of a Queue Examples: A Reservation Counter Jobs in a printer A queue of ready jobs waiting for the processor.

1.10. QUEUE ADT

29

1.10.1

Basic Operations Of Queue ADT:

The basic operations that can be done on a queue are, Enqueue Dequeue Enqueue: An enqueue operation adds a new element in a queue This process is carried out by incrementing the rear end and adding a new element at the rear end position. The syntax for inserting a new element into a queue. Enqueue(Q,X) (or) Insert(Q,X) The element X inserted into a queue Q. Dequeue: A dequeue operation removes the rst element from the queue. A dequeue operation is carried out by incrementing the front end and deleting the rst element at athe front end position. The syntax for removing a rst element from the queue. Dequeue(Q) (or) Delete(Q) Here, the rst element is removed from the queue. Queue ADT: Queue is a linear data structure that permits insertion of new element at one end and deletion of an element at the other end. The end at which the deletion of an element take place is called front, and the end at which insertion of a new element can take place is called rear. The deletion or insertion of elements can take place only at the front or rear end of the list respectively.The rst element that gets added into the queue is the rst one to get removed from the list. Hence, queue is also referred to as First-In-First-Out list (FIFO). Types Of Queue: There are dierent types of queue Linear Queue Circular Queue Deque Linear Queue: A queue is referred to as the linear queue. The queue has two ends such as front end and rear end. The rear end is where we insert the elements and the front end is where we delete the elements. In a linear queue , we can traverse in only one direction. In a linear queue if the front pointer is in rst position, and the rear pointer is in the last position then the queue is said to be fully occupied. Initially, the front and rear ends are at the same position(Intialized to -1.) When we insert the elements, the rear pointer moves one by one until the last index position is reached.(the front pointer doesnt change.) When we delete the elements, the front pointer moves one by one until the rear pointer is reached.(the rear pointer doesnt change.) If the front and rear pointer positions are initialized to -1, then the queue is said to be empty. e Circular Queue: Circular Queue is another form of a linear queue in which the last position is connected to the rst position of the list. It is similar to linear queue has two ends such as front and rear ends. The rear end is where we insert the elements and front end is where we delete the elements. In a circular queue we can traverse in only one direction. Initially, front and rear ends are at the same position. When we insert an element, the rear pointer moves one by one until the front end is reached.(front end doesnt change.)

30

CHAPTER 1. LINEAR STRUCTURES

If the next position of the rear is front , then the queue is said to be fully occupied. When we delete an element, the front pointer moves one by one until the rear end is reached. If the front end reaches the rear end, then the queue is said to be empty. Deques:

Figure 1.11: Representation Of Circular Queue Deques means Double-Ended Queue. It is another form of a queue in which insertion and deletions are made at the both front and rear ends of the queue. There are two types of deques. Input Restricted Deque. Output Restricted Deque. The input restricted deque allows insertions at one end(it can be either front (or) rear). The output restricted deque allows deletions at one end(it can be either front (or) rear). Implementation Of Queue:

Figure 1.12: Representation Of a Queue A queue can be implemented in two ways. Array Implementation Of Linear Queue. LinkedList Implementation Of linear Queue.

1.10.2

Representation Of Linear Queue Using Array:

One of the simplest way of representing a queue is by means of single dimensional array. Queues and arrays are ordered collection of elements . The number of elements in the array is xed. But the size of a queue is constantly changed when the elements are enqueued and dequeued. The queue is stored in a part of the array, so an array can be declared large enough to hold the max no of elements of the queue. During execution of the program,the queue size can be varied with in the space reserved for it. If queue is implemented using arrays, the size of the array should be xed maximum allowing the queue to expand or shrink.

1.10. QUEUE ADT All the basic operations performed on the queue by using array. The basic operations are, Creation Insertion Deletion

31

Algorithm for creating a Queue: Creation of a queue requires the declaration of an array and initializing front and rear end indicates to -1 respectively. Algorithm CreateQ(Queue Q)

Figure 1.13: Queue Begin Q.front -1 Q.rear -1 End. Algorithm for Insertion: Insertion requires incrementing the rear pointer and storing the value. Algorithm Insert(Q,front,rear,N,X) Begin if(rear=N-1) then Write Queue Overow else rear rear+1 Q[rear] X if(front= -1) then front rear end if end if End. Algorithm for Deletion: Deletion requires extracting the elements and incrementing the front pointer. Algorithm Deletion(Q,front,rear) Begin if(front=-1)then WriteQueue Underow else if(front=rear) then front rear -1 else front front+1 end if end if End.

32

CHAPTER 1. LINEAR STRUCTURES

1.10.3

Linked List Implementation Of Queue

One of the way of representing the queue is by means of a singly linked list. This representation has more advantages than representing queue using arrays. The advantages are, It is not necessary to specify the no of elements to be stored in a queue during its declaration. Insertions and deletions can be handled easily an d eciently. Linked List representation of queue can grow and shrink in size without wasting the memory space,depending upon the insertion and deletion that occurs in the list. The basic operations can be performed on the queue are, Enqueue Dequeue Algorithm for inserting an element into a queue: Algorithm Enqueue(Head,X) Begin Temp- Newnode Data(Temp) X Next(Temp) NULL If(head==NULL) then Head Temp Else Temp1 Head While(Next(temp1)!=NULL) Temp1 Next(Temp1) end while Next(Temp1) Temp End if End. Algorithm for Deleting an Element From the Queue: Algorithm dequeue(Queue,front,rear) Begin if(front=NULL AND rear=NULL) WriteQueue Underow Set temp front Set value=front data if(front==rear) set rear=NULL set front=front next Releasenode(temp) End.

1.11 1.12

CIRCULAR QUEUE IMPLEMENTATION APPLICATIONS OF QUEUE ADT

The applications of queue are, Priority Queue

1.12. APPLICATIONS OF QUEUE ADT Scheduling Algorithms

33

Priority Queue: A priority queue is a collection of elements in which the elements are added at the end and the high priority element is deleted. In a priority queue each and every elements containing a key referred as the priority for that elements. The operations performed in a queue are similar to the queue except that the insertion and deletion elements made in it. Elements can be inserted in any order, but are arranged in order of their priority. The elements are deleted from the queue in the order of their priority. The elements with the same priority are given equal importance and processed accordingly. The priority queue can be implemented in the following ways. Ordered List Implementation Of Priority Queue. Heap Implementation Of Priority Queue. Applications: Modeling of systems, where the keys might correspond to event times to be processed in chronological order. CPU scheduling in computer systems, where the keys might correspond to priorities indicating which processes are to be served rst. Numerical computations where the keys might be computational errors indicating that the largest should be dealt with rst.

34

CHAPTER 1. LINEAR STRUCTURES

Chapter 2

UNIT-II
2.1 TREE STRUCTURES

Tree is a non-linear data structures.

2.2
2.2.1

TREE ADT
Basic Terminologies:

A tree is a non-linear data structure that is used to represents hierarchical relationships between individual data items. Tree: A tree is a nite set of one or more nodes such that, there is a specially designated node called root. The remaining nodes are partitioned into n=0 disjoint sets T1, T2,..Tn, where each of these set is a tree T1,Tn are called the subtrees of the root. Branch: Branch is the link between the parent and its child. Leaf: A node with no children is called a leaf. Subtree: A Subtree is a subset of a tree that is itself a tree. Degree: The number of subtrees of a node is called the degree of the node. Hence nodes that have degree zero are called leaf or terminal nodes. The other nodes are referred as non-terminal nodes. Children: The nodes branching from a particular node X are called children of X and X is called its parent. Siblings: Children of the same parent are said to be siblings. Degree of tree: Degree of the tree is the maximum of the degree of the nodes in the tree. Ancestors: 35

36

CHAPTER 2. UNIT-II

Ancestors of a node are all the nodes along the path from root to that node. Hence root is ancestor of all the nodes in the tree. Level: Level of a node is dened by letting root at level one. If a node is at level L, then its children are at level L + 1. Height or depth: The height or depth of a tree is dened to be the maximum level of any node in the tree. Climbing: The process of traversing the tree from the leaf to the root is called climbing the tree. Descending: The process of traversing the tree from the root to the leaf is called descending the tree.

Figure 2.1: Structure Of Tree

2.3

TREE TRAVERSALS

There are three standard ways of traversing a binary tree T with root R. They are: Preorder Traversal Inorder Traversal Postorder Traversal General outline of these three traversal methods can be given as follows:

2.3. TREE TRAVERSALS

37

2.3.1

Preorder Traversal

(1) Process the root R. (2) Traverse the left subtree of R in preorder. (3) Traverse the right subtree of R in preorder.

2.3.2

Inorder Traversal

(1) Traverse the left subtree of R in inorder. (2) Process the root R. (3) Traverse the right subtree of R in inorder.

2.3.3

Postorder Traversal

(1) Traverse the left subtree of R in postorder. (2) Traverse the right subtree of R in postorder. (3) Process the root R. Observe that each algorithm contains the same three steps, and that the left subtree of R is always traversed before the right subtree. The dierence between the algorithms is the time at which the root R is processed. The three algorithms are sometimes called, respectively, the node-left-right (NLR) traversal, the left-node-right (LNR) traversal and the left-right-node (LRN) traversal. Now we can present the detailed algorithm for these traversal methods in both recursive method and iterative method. Traversal algorithms using recursive approach Preorder Traversal: In the preorder traversal the node element is visited rst and then the right subtree of the node and then the right subtree of the node is visited. Consider the following case where we have 6 nodes in the tree A, B, C, D, E, F. The traversal always starts from the root of the tree. The node A is the root and hence it is visited rst. The value at this node is processed. The processing can be doing some computation over it or just printing its value. Now we check if there exists any left child for this node if so apply the preorder procedure on the left subtree. Now check if there is any right subtree for the node A, the preorder procedure is applied on the right subtree. Since there exists a left subtree for node A, B is now considered as the root of the left subtree of A and preorder procedure is applied. Hence we nd that B is processed next and then it is checked if B has a left subtree. This recursive method is continued until all the nodes are visited.

The algorithm for the above method is presented in the pseudo-code form below: Algorithm: PREORDER( ROOT ) Temp = ROOT If temp = NULL Return End if Print info(temp) If left(temp) ? NULL PREORDER( left(temp)) End if If right(temp) ? NULL PREORDER(right(temp))

38

CHAPTER 2. UNIT-II

Figure 2.2: Tree Traversal

End if End PREORDER Inorder Traversal: In the Inorder traversal method, the left subtree of the current node is visited rst and then the current node is processed and at last the right subtree of the current node is visited. In the following example, the traversal starts with the root of the binary tree. The node A is the root and it is checked if it has the left subtree. Then the inorder traversal procedure is applied on the left subtree of the node A. Now we nd that node D does not have left subtree. Hence the node D is processed and then it is checked if there is a right subtree for node D. Since there is no right subtree, the control returns back to the previous function which was applied on B. Since left of B is already visited, now B is processed. It is checked if B has the right subtree. If so apply the inroder traversal method on the right subtree of the node B. This recursive procedure is followed till all the nodes are visited. Algorithm: INORDER( ROOT ) Temp = ROOT If temp = NULL Return End if If left(temp) ? NULL INORDER(left(temp)) End if Print info(temp) If right(temp) ? NULL INORDER(right(temp)) End if End INORDER Postorder Traversal:

2.3. TREE TRAVERSALS

39

Figure 2.3: Tree Traversal

In the postorder traversal method the left subtree is visited rst, then the right subtree and at last the current node is processed. In the following example, A is the root node. Since A has the left subtree the postorder traversal method is applied recursively on the left subtree of A. Then when left subtree of A is completely is processed, the postorder traversal method is recursively applied on the right subtree of the node A. If right subtree is completely processed, then the current node A is processed.

Algorithm: POSTORDER( ROOT ) Temp = ROOT If temp = NULL Return End if If left(temp) ? NULL POSTORDER(left(temp)) End if If right(temp) ? NULL POSTORDER(right(temp)) End if Print info(temp) End POSTORDER

40

CHAPTER 2. UNIT-II

Figure 2.4: Tree Traversal

2.3.4

BINARY TREE ADT

Binary tree has nodes each of which has no more than two child nodes. A binary tree is a nite set of nodes that either is empty or consists of a root and two disjoint binary trees called the left subtree and right subtree. Left child: The node present to the left of the parent node is called the left child. Right child: The node present to the right of the parent node is called the right child. Skewed Binary tree: If the new nodes in the tree are added only to one side of the binary tree then it is a skewed binary tree. Strictly binary tree: If the binary tree has each node consisting of either two nodes or no nodes at all, then it is called a strictly binary tree. Complete binary tree: If all the nodes of a binary tree consist of two nodes each and the nodes at the last level does not consist any nodes, then that type of binary tree is called a complete binary tree. It can be observed that the maximum number of nodes on level i of a binary tree is 2i - 1, where i ? 1. The maximum number of nodes in a binary tree of depth k is 2k - 1, where k ? 1.

Representation Of Binary Trees There are two ways in which a binary tree can be represented. They are: (i) Array representation of binary trees. (ii)Linked representation of binary trees. Array Representation Of BinaryTrees: When arrays are used to represent the binary trees, then an array of size 2k is declared where, k is the depth of the tree. For example if the depth of the binary tree is 3, then maximum 23 - 1 = 7 elements will be present in the node and hence the array size will be 8. This is because the elements are stored from position one leaving

2.4. EXPRESSION TREES

41

Figure 2.5: Types Of Tree

the position 0 vacant. But generally an array of bigger size is declared so that later new nodes can be added to the existing tree. The following binary tree can be represented using arrays as shown. The root element is always stored in position 1. The left child of node i is stored in position 2i and right child of node is stored in position 2i + 1. Hence the following formulae can be used to identify the parent, left child and right child of a particular node. Parent( i ) = i / 2, if i ? 1. If i = 1 then i is the root node and root does not has parent. Left child( i ) = 2i, if 2i ? n, where n is the maximum number of elements in the tree. If 2i n, then i has no left child. Right child( i ) = 2i + 1, if 2i + 1 ? n. If 2i + 1 n, then i has no right child. The empty positions in the tree where no node is connected are represented in the array using -1, indicating absence of a node. Using the formula, we can see that for a node 3, the parent is 3/ 2 1. Referring to the array locations, we nd that 50 is the parent of 40. The left child of node 3 is 2*3 6. But the position 6 consists of -1 indicating that the left child does not exist for the node 3. Hence 50 does not have a left child. The right child of node 3 is 2*3 + 1 7. The position 7 in the array consists of 20. Hence, 20 is the right child of 40. Linked Representation Of Binary Trees: In linked representation of binary trees, instead of arrays, pointers are used to connect the various nodes of the tree. Hence each node of the binary tree consists of three parts namely, the info, left and right. The info part stores the data, left part stores the address of the left child and the right part stores the address of the right child. Logically the binary tree in linked form can be represented as shown. The pointers storing NULL value indicates that there is no node attached to it. Traversing through this type of representation is very easy. The left child of a particular node can be accessed by following the left link of that node and the right child of a particular node can be accessed by following the right link of that node.

2.4

EXPRESSION TREES

The trees are many times used to represent an expression and if done so, those types of trees are called expression trees. The following expression is represented using the binary tree, where the leaves represent the operands and the internal nodes represent the operators.

42

CHAPTER 2. UNIT-II

Figure 2.6: Array Representation Of Binary Tree

Figure 2.7: Linked Representation Of Binary Tree

2.5

APPLICATIONS OF TREES

The applications of the trees are, Human Coding Decoding

2.6

BINARY SEARCH TREE ADT

Binary Search Tree: Binary Search Tree is a binary tree which could either be empty (or) with the following properties: The elements in the left subtree are less than the element in the root The elements in the right subtree are greater than the element in the root The left and right subtrees are in turn binary search tree.

2.6. BINARY SEARCH TREE ADT

43

Figure 2.8: Binary Search Tree

2.6.1

Basic Operations:

Creation Insertion Deletion Searching Creation: Creating a node using getnode(). The getnode() allocating the memory space for the node. Read details for the node from the user using readnode() method. Insert the node in the binary search tree. Insertion: Inserting an element into binary search tree should not aect its basic ordering properties: The key value of the node should be compared with that of root. If it is less than it should be added in the left subtree otherwise in the right subtree Similar comparison should be made in the left (or) right subtree The new element added will always be at the leaf level Routine For Insertion: SearchTreeInsert(int x,SearchTree T) Begin if(T==NULL) T=malloc(sizeof(struct Tree Node)) T Element=X; T left=NULL; T right=NULL; else if(XT Element) T left=Insert(X,T left); else if( X T Element) T right=Insert(X,T Right); return T;

44 End. Example: Insert the following elements into the BinarySearchTree 40,25,60,36,27,70. Solution: Step1:

CHAPTER 2. UNIT-II

Figure 2.9: Binary Search Tree Step2: Next, the element 25 is compared with the root node 40(2540). So add it to the left subtree of root 40.

Figure 2.10: Binary Search Tree Step 3: Next the element 60 compared with the root node 40 ( 6040). So add 60 to the right child of 40. Step 4: Next the element 36 compared with the root node 40. As 3640, so move to the left subtree and compare with the root of the left subtree 25. As 3625, so add it to the right subtree of root 25. Step 5: (i) Compare 40 and 27. (ii) As 2740,move to the left subtree (iii) Compare 25 and 27. (iv) As 2725,move to the right. (v) Compare 27 and 36 (vi) As 27 36 , so add 27 to the left child. Step 6: (i) Compare 40 and 70

2.6. BINARY SEARCH TREE ADT

45

Figure 2.11: Binary Search Tree

Figure 2.12: Binary Search Tree (ii) As 7040, so move to the right (iii) Compare 70 and 60. (iv) As 70 60 so add 70 to the right child of 60.

2.6.2

Deletion:

A node to be deleted can ll into any one of the following categories: Node may not have any children(Leaf node) Node may have only one child(Either left/right child) Node may have two children(Both left and right) Case 1: Deleting a Leaf node: Search the parent of the leaf node and make the link to the parent node as NULL. Release the memory for the deleted node. Example: CASE 2: Deleting a leaf node with only one child Search the parent of the node to be deleted (with only one child] Assign the link of the parent node to the child of the root to be deleted. Release the memory for the deleted node. Example: CASE 3: Deleting a node with two children The general strategy is to replace the data of the node to be deleted with its smallest data of the right subtree and recursively delete the node.

46

CHAPTER 2. UNIT-II

Figure 2.13: Binary Search Tree

Figure 2.14: Binary Search Tree Example: Routine For Deletion: SearchTreeDelete(int x,SearchTree T) Begin int Tmpcell; if(T==NULL) Error(Element not found); else if(XT Element) T left=Delete(X,T left) if(XT Element) T right=Delete(X,T right) else if(T left && T right) Tmpcell = FindMin(T right) T Element=Tmpcell Element T right=Delete(T Element ,T right) else Tmpcell=T; if(T left==NULL)

2.6. BINARY SEARCH TREE ADT

47

Figure 2.15: Binary Search Tree

Figure 2.16: Binary Search Tree T=T right else if(T right==NULL) T=T left free(Tmpcell) return T Search Operation in a Binary Search Tree: Searching is the most primitive operation performed on binary search tree. Searching starts from root of the tree If the search key value is less than that in root, then the possible position of the element in the left subtree. f the search key value is greater than that in root, then the possible position of the element in the right subtree. This searching process should continue till the node with the search key value (or) a null pointer(at the end of the branch is reached) In case, a null pointer is reached it is an indication of the absence of the node. Routine For Searching: IntFind(int X ,SearchTree T) Begin if(T==NULL) Return NULL; if(XT Element) return nd(X,T left) else if(XT Element)

48

CHAPTER 2. UNIT-II

Figure 2.17: Binary Search Tree

Figure 2.18: Binary Search Tree return nd(X,T right) else return T End. The reason why we go for a Binary Search tree is to improve the searching eciency. The average case time complexity of the search operation in a binary search tree is O( log n ).

2.7

THREADED BINARY TREES

In linked list representation of binary trees we can see that all leaf nodes and some non leaf node contains the null values. Instead of storing the null value in the left and right pointer elds, we can store some useful information such as inorder predecessor in the left pointer eld and inorder successor in the right pointer eld. These links are considered as threads . A binary tree which implements these threads are referred to as threaded binary tree. The left pointer elds as threads only used in the binary tree is referred as left -in threaded binary tree. The right pointer elds as threads only used in the binary tree is referred to as the right in threaded binary tree. Both the left and right pointer elds as threads used I binary tree is referred to as fully in threaded binary

2.7. THREADED BINARY TREES

49

Figure 2.19: Binary Search Tree tree.

Figure 2.20: Threaded Binary Tree

2.7.1

Basic Operations In Threaded Binary Tree:

The basic operations that can be performed on a threaded binary tree. Creation of threaded binary tree. Insertion of node Deletion of node Searching a node Modication of node Inorder traversal of threaded binary tree Preorder traversal of threaded binary tree Post order traversal of threaded binary tree View the contents of threaded binary tree

50 Creation Of Threaded Binary Tree:

CHAPTER 2. UNIT-II

Every node in the threaded binary tree has three parts data part, link part and thread ag. Creation process involves three processes. They are, Creating the node Read the details for the node from the user Insert the node in the threaded binary tree. Insertion Of a Node: 1. One of the most primitive operation performed in a threaded binary tree is the insertion of the node. 2. Memory is to be allocated for the new node before reading the data. 3. The new node will contain the empty data eld and empty link eld and an empty thread ag. 4. The data eld of the new node is then stored with the information read from the user. 5. The link eld of the new node is assigned to NULL. The thread ag of the new node is set for both the left and right threads.

Deletion Of a Node: 1. Another Primitive operation that can be done in a threaded binary tree is the deletion of a node. Memory is to be deleted. 2. A node can be deleted from the tree from three dierent places namely, Deleting a leaf node Deleting a node with only one child Deleting a node with two children. (a) Deleting a leaf node: 1. Search the location and parent of the node to be deleted. 2. Compare the parent node data for the following three conditions 3. If the parent node is empty, it means that the threaded binary tree contains only one node , hence the tree becomes empty after deletion of the node and returns NULL. 4. If the node to be deleted is the left child of the parent node , perform the following two operations Set the left thread ag of the parent node 5. The left child of the node to be deleted is assigned to left child of the parent. 6. If the node to be deleted is the right child of the parent node perform the following two operations (a). Set the right thread ag of the parent node (b). The right child of the node to be deleted is assigned to right child of the parent. (c). Release the memory for the node to be deleted. (b) Deleting a node with only one child: Steps followed to delete the node from the threaded binary tree. 1. Search the location and parent of the node to be deleted with only one child. 2. Copy the location of the child node. 3. Compare the parent node data for the following three conditions. 4. If the parent node is empty, it means that the threaded binary tree contains two nodes. Now assign the location of the child node as the root node. 5. If the node to be deleted is the left child of the parent node, assign the location of the child node as the left child of the parent node 6. If the node to be deleted is the right child of the parent node , assign the location of the child node as the right child of the parent node. 7. Find the inorder predecessor and successor for the location. 8. The left child of the iniorder successor of the location is inorder predecessor of the location. 9. The right child of the iniorder predecessor of the location is inorder successor of the location.

2.7. THREADED BINARY TREES

51

10. Release the memory for the node to be deleted. Deleting a node with two children: Steps followed to delete the node from the threaded binary tree. 1.Search the location and parent of the node to be deleted with two child. 2.Delete the inorder successor of the location, and replace the deleted node with inorder successor. If the inorder successor of the location has no child, follow the steps given in the deleting a leaf node. If the inorder successor node has only one child follow the steps given in the deleting the node with only one child. 3.Replace the contents of the node to be deleted with the contents of the inorder successor node. 4.Release the memory for the inorder successor of the node to be deleted. Displaying the Contents Of the Threaded Binary Tree: 1. To display the information in a threaded binary tree, we have to traverse the threaded binary tree. 2. The contents of the threaded binary tree is displayed in 90 degree anti clockwiseposition, to view the contents of the threaded binary tree in the fashion of the tree. 3. The following traversal techniques performed on the threaded binary tree such as, Inorder traversal Preorder Traversal Post order traversal Level Order Traversal.

52

CHAPTER 2. UNIT-II

Chapter 3

UNIT-III
3.1 HEIGHT BALANCED TREES ( AVL TREES )

The Height balanced trees were developed by researchers Adelson-Velskii and Landis. Hence these trees are also called AVL trees. Height balancing attempts to maintain the balance factor of the nodes within limit. Height of the tree: Height of a tree is the number of nodes visited in traversing a branch that leads to a leaf node at the deepest level of the tree. Balance factor: The balance factor of a node is dened to be the dierence between the height of the nodes left subtree and the height of the nodes right subtree. Consider the following tree. The left height of the tree is 5, because there are 5 nodes (45, 40, 35, 37 and 36) visited in traversing the branch that leads to a leaf node at the deepest level of this tree. Balance factor = height of left subtree - height of the right subtree In the following tree the balance factor for each and every node is calculated and shown. For example, the balance factor of node 35 is (0 - 2 ) = - 2. The tree which is shown below is a binary search tree. The purpose of going for a binary search tree is to make the searching ecient. But when the elements are added to the binary search tree in such a way that one side of the tree becomes heavier, then the searching becomes inecient. The very purpose of going for a binary search tree is not served. Hence we try to adjust this unbalanced tree to have nodes equally distributed on both sides. This is achieved by rotating the tree using standard algorithms called the AVL rotations. After applying AVL rotation, the tree becomes balanced and is called the AVL tree or the height balanced tree. The tree

Figure 3.1: AVL Trees 53

54

CHAPTER 3. UNIT-III

is said to be balanced if each node consists of a balance factor either -1 or 0 or 1. If even one node has a balance factor deviated from these values, then the tree is said to be unbalanced. There are four types of rotations. They are: Left-of-Left rotation. Right-of-Right rotation. Right-of-Left rotation. Left-of-Right rotation.

3.1.1

Left-of-Left Rotation:

Consider the following tree. Initially the tree is balanced. Now a new node 5 is added. This addition of the new node makes the tree unbalanced as the root node has a balance factor 2. Since this is the node which is disturbing the balance, it is called the pivot node for our rotation. It is observed that the new node was added as the left child to the left subtree of the pivot node. The pointers P and Q are created and made to point to the proper nodes as described by the algorithm. Then the next two steps rotate the tree. The last two steps in the algorithm calculates the new balance factors for the nodes and is seen that the tree has become a balanced tree.

Figure 3.2: Left Of Left Rotation

Algorithm: LEFT-OF-LEFT(pivot) P = left(pivot) Q = right(P) Right(P) = pivot Left(pivot) = Q Pivot = P Bal(pivot) = 0 Bal(right(pivot)) = 0 End LEFT-OF-LEFT

3.1.2

Right-of-Right Rotation:

In this case, the pivot element is xed as before. The new node is found to be added as the right child to the right subtree of the pivot element. The rst two steps in the algorithm sets the pointer P and Q to the

3.1. HEIGHT BALANCED TREES ( AVL TREES )

55

correct positions. The next two steps rotate the tree to balance it. The last two steps calculate the new balance factor of the nodes.

Figure 3.3: Right Of Right Rotation

Algorithm: RIGHT-OF-RIGHT(pivot) P = right(pivot) Q = left(P) Left(P) = pivot Right(pivot) = Q Pivot = P Bal(pivot) = 0 Bal(left(pivot)) = 0 End RIGHT-OF-RIGHT

3.1.3

Right-of-Left Rotation:

In this following tree, a new node 19 is added. This is added as the right child to the left subtree of the pivot node. The node 20 xed as the pivot node, as it disturbs the balance of the tree. In the rst two steps the pointers P and Q are positioned. In the next four steps, tree is rotated. In the remaining steps, the new balance factors are calculated. Algorithm: RIGHT-OF-LEFT(pivot) P = left(pivot) Q = right(P) Left(pivot) = right(Q) Right(P) = left(Q) Left(Q) = P Right(Q) = pivot Pivot = Q If Bal(pivot) = 0 Bal(left(pivot)) = 0 Bal(right(pivot)) = 0

56

CHAPTER 3. UNIT-III

Figure 3.4: Right Of Left Rotation

Else If Bal(pivot) = 1 Bal(pivot) = 0 Bal(left(pivot)) = 0 Bal(right(pivot)) = -1 Else Bal(pivot) = 0 Bal(left(pivot)) = 1 Bal(right(pivot)) = 0 End if End if End RIGHT-OF-LEFT

3.1.4

Left-of-Right:

In the following tree, a new node 21 is added. The tree becomes unbalanced and the node 20 is the node which has a deviated balance factor and hence xed as the pivot node. In the rst two steps of the algorithm, the pointers P and Q are positioned. In the next 4 steps the tree is rotated to make it balanced. The remaining steps calculate the new balance factors for the nodes in the tree. Algorithm: LEFT-OF-RIGHT(pivot) P = right(pivot) Q = left(P) Right(pivot) = left(Q) Left(P) = right(Q) Right(Q) = P Left(Q) = pivot Pivot = Q If Bal(pivot) = 0 Bal(right(pivot)) = 0 Bal(left(pivot)) = 0 Else If Bal(pivot) = 1 Bal(pivot) = 0

3.2. SPLAY TREES

57

Figure 3.5: Left Of Right Rotation Bal(right(pivot)) = 0 Bal(left(pivot)) = -1 Else Bal(pivot) = 0 Bal(right(pivot)) = 1 Bal(left(pivot)) = 0 End if End if End LEFT-OF-RIGHT

3.2

SPLAY TREES

The splay tree is a simple data structure. The splay tree was developed by Daniel Sleator and Robert Tonjan. Basically, the splay tree is the binary tree search tree. The binary search tree is a binary tree and it has the property of left child value should be lesser than the root node value and the right child value should be greater than the root node value. The splay tree has some additional properties such as the most recently referred node can be quickly accessed in future. The splay tree that guarantees that any M-consecutive tree operations starting from an empty tree take at most O (M log N) time. The basic idea of the splay tree is that after a node is accessed, it is pushed to the root by a series of rotations. If a node is deep, there are many nodes on the path that are also relatively deep,and by restructuring , we can make future accesses cheaper on all these nodes.Splay tree also do not require the maintenance of height (or) balance information, thus saving the space.

3.2.1

Splaying:

Splaying is similar to the rotations. The need for splaying operations is that the most recently referred item (or) node can be quickly accessed

58

CHAPTER 3. UNIT-III

in future. The splaying operation is to make the most recently referred node as the root node. The following factors are used for performing the splaying operations. If x is a left child/ right child to p If p is a left child/ right child to g. The splaying operations can be classied into three categories. If g=NULL / g!= NULL Zig Operation. Zig-Zig Operation Zig-Zag Operation Zig Operation: When the grandparent(g) is null then the zig operation is performed. The newly inserted element as the left child of the parent node, then restructuring the tree by performing the right rotation with respect to the parent node p of x .Then , we get the balanced tree. Case(i) : X is the left child of P

Figure 3.6: Zig Operation

Case(ii) : X is the right child of P

Figure 3.7: Zig Operation

3.2. SPLAY TREES Zig-Zig operation:

59

When grandparent (g) is not null, then the zig-zig operation is performed. The newly inserted element x as the left child of parent p and the parent node p as the left child of grandparent g. After inserting an element by restructuring the tree the double rotations performed on the right side based on the parent node and grandparent node. Case (i): X and P are the left side children.

Figure 3.8: Zig-zig Operation

Case (ii):X and P are the right side children. In this case, after inserting an element restructuring the tree by performing the double left rotation based on the grand parent and parent node.

Figure 3.9: Zig-zig Operation

Zig-Zag Operation: When the grand parent (g) is not null then the zig-zag operation is performed. The newly inserted element x as theleft child of the parent node and p as the right child of grand parent node g. After inserting an element restructuring the tree by performing the double rotations based on the parent node and the grand

60

CHAPTER 3. UNIT-III

parent node. Case (i): X is a left child of P and P is the right child of G. In this case, rst do the right rotation with respect to p after that do the left rotation with respect to g.

Figure 3.10: Zig-zag Operation

Case (ii): If X is a right child of P and P is a left child of G. In this case, rst do the left rotation with respect to p after that do the right rotation with respect to g.

Figure 3.11: Zig-zag Operation

3.3

B-TREE

Multiway search tree (m-way search tree): Multiway search tree of order n is a tree in which any node may contain maximum n-1 values and can have maximum n children. Consider the following tree.

3.3. B-TREE

61

Every node in the tree has one or more than one values stored in it. The tree shown is of order 3. Hence this tree can have maximum 3 children and each node can have maximum 2 values. Hence it is an m-way search tree.

Figure 3.12: B-Tree

3.3.1

B - Tree:

B - tree is a m-way search tree of order n that satises the following conditions. 1. All non-leaf nodes (except root node) have at least n/2 children and maximum n children. 2. The non-leaf root node may have at least 2 children and maximum n children. 3. B-Tree can exist with only one node. i.e. the root node containing no child. 4. if a node has n children then it must have n-1 values. 5. All the values that appear on the left most child of a node are smaller than the rst value of that node All values that appears on the right most child of a node are greater that the last values of that node. 6. If x and y are any two ith and (i+1)th values of a node, where x y, then all the values appearing on the (i+1)th sub-tree of that node are greater than x and less than y. 7. All the leaf nodes should appear on the same level. All the nodes except root node should have minimum n/2 values. Consider the following tree. Clearly, it is a m-way search tree of order 3. Let us check whether the above conditions are satised. It can be seen that root node has 3 children and therefore has only 2 values stored in it. Also it is seen that the elements in the rst child (3, 17) are lesser than the value of the rst element (23) of the root node. The value of the elements in the second child (31) is greater than the value of the rst element of the root node (23) and less than the value of the second element (39) in the root node. The value of the elements in the rightmost child (43, 65) is greater than the value of the rightmost element in the root node. All the three leaf nodes are at the same level (level 2). Hence all the conditions specied above is found to be satised by the given m-way search tree. Therefore it is a B-Tee.

Figure 3.13: B-Tree

62

CHAPTER 3. UNIT-III

3.3.2

Search Operation in a B-Tree:

Let us say the number to be searched is k = 64. A temporary pointer temp is made to initially point to the root node. The value k = 64 is now compared with each element in the node pointed by temp. If the value is found then the address of the node where it is found is returned using the temp pointer. If the value k is greater than ith element of the node, then the temp is moved to the i+1th node and the search process is repeated. If the k value is lesser than the rst value in the node, then the temp is moved to the rst child. If the k value is greater than the last value of the node, then temp is moved to the rightmost child of the node and the search process is repeated. After the particular node where the value is found is located (now pointed by temp), then a variable LOC is initialized to 0, indicating the position of the value to be searched within that node. The value k is compared with each and every element of the node. When the value of the k is found within the node, then the search comes to an end position where it is found is stored in LOC. If not found the value of LOC is zero indicating that the value is not found.

Figure 3.14: Searching in B-Tree Algorithm: SEARCH( ROOT, k ) Temp = ROOT, i = 1, pos = 0 While i ? count(temp) and child[i](temp) ? NULL If k = info(temp[i]) Pos = i Return temp Else If k info(temp[i]) SEARCH(child[i](temp), k) Else If i = count(temp) Par = temp Temp = child[i+1](temp) Else i=i+1 End if End if End if End While While i ? count(temp) If k = info(temp[i]) Pos = i Return temp End if End while End SEARCH

3.3. B-TREE

63

3.3.3

Insert Operation in a B-Tree:

One of the conditions in the B-Tree is that, the maximum number of values that can be present in the node of a tree is n - 1, where n is the order of the tree. Hence, it should be taken care that, even after insertion, this condition is satised. There are two cases: In the rst case, the element is inserted into a node which already had less than n- 1 values, and the in the second case, the element is inserted into a node which already had exactly n-1 values. The rst case is a simple one. The insertion into the node does not violate any condition of the tree. But in the second case, if the insertion is done, then after insertion, the number values exceeds the limit in that node. Let us take the rst case. In both the cases, the insertion is done by searching for that element in the tree which will give the node where it is to be inserted. While searching, if the value is already found, then no insertion is done as B-Tree is used for storing the key values and keys do not have duplicates. Now the value given is inserted into the node. Consider the gure which shows how value 37 is inserted into correct place. In the second case, insertion is done as explained above. But now, it is

Figure 3.15: Insertion Operation in B-Tree found that, the number of values in the node after insertion exceeds the maximum limit. Consider the same tree shown above. Let us insert a value 19 into it. After insertion of the value 19, the number of values (2, 13, 19, 22) in that node has become 4. But it is a B-Tree of order 4 in which there should be only maximum 3 values per node. Hence the node is split into two nodes, the rst node containing the numbers starting from the rst value to the value just before the middle value (rst node: 2). The second node will contain the numbers starting just after the mid value till the last value (second node: 19, 22). The mid value 13 is pushed into the parent. Now the adjusted B-Tree appears as shown.

Figure 3.16: Insertion in B-Tree Algorithm: INSERT( ROOT, k ) Temp = SEARCH( ROOT, k ) If count(temp) n-1 Ins(temp, k) Return Else Repeat for i = n/2 +1 to n-1 Info(R[i-n/2]) = info(temp[i]) Count(R) = count(R) + 1 End repeat Count(temp) = n/2 - 1 Ins(par, info(temp[m/2])

64 End if INSERT( ROOT, k ) End INSERT

CHAPTER 3. UNIT-III

3.3.4

Delete Operation in B-Tree:

When the delete operation is performed, we should take care that even after deletion, the node has minimum n/2 value in it, where n is the order of the tree. There are three cases: Case 1: The node from which the value is deleted has minimum n/2 values even after deletion. Let us consider the following B-Tree of order 5. A value 64 is to be deleted. Even after the deletion of the value 64, the node has minimum n/2 values (i.e., 2 values). Hence the rules of the B-Tree are not violated.

Figure 3.17: Deletion in B-Tree Case 2: In the second case, after the deletion the node has less than minimum n/2 values. Let us say we delete 92 from the tree. After 92 is deleted, the node has only one value 83. But a node adjacent to it consist 3 values (i.e., there are extra values in the adjacent node). Then the last value in that node 71 is pushed to its parent and the rst value in the parent namely 79 is pushed into the node which has values less than minimum limit. Now the node has obtained the minimum required values.

Figure 3.18: Deletion in B-Tree

3.3. B-TREE

65

Case 3: In the previous case, there was an adjacent node with extra elements and hence the adjustment was made easily. But if all the nodes have exactly the minimum required, and if now a value is deleted from a node in this, then no value can be borrowed from any of the adjacent nodes. Hence as before a value from the parent is pushed into the node (in this case 32 is pushed down). Then the nodes are merged together. But we see that the parent node has insucient number of values. Hence same process of merging takes place recursively till the entire tree is adjusted.

Figure 3.19: Deletion in B-Tree Algorithm: DELETE( ROOT, K ) Temp = SEARCH( ROOT, k ), DELETED = 0, i = 1 While i = count(temp) If (k = info(temp[i]) DELETED = 1 Delete temp[i] End if End while If DELETED = 0 Print Item not found Return Else If count(temp) n / 2 i=1 While i = count(par) If count(child[i](par)) n/2 s = child[i](par) break Else i=i+1 End if End while If info(temp[1]) info(s[count(s)]) Ins(temp, info(par[1])) Ins(par, info(s[count(s)])) Else Ins(temp, info(par[count(par)])) Ins(par, info(s[1]))

66 End End End End if if if DELETE

CHAPTER 3. UNIT-III

3.4
3.4.1

HEAPS
Denition Of Heaps

Suppose H is a complete a binary tree with n elements, then H is called a heap, or a maxheap, if each node N of H has the following property : The value at N is greater than or equal to the value at each of the children of N. A minheap is a heap, where the value at N is lesser than or equal to the value at each of the children of N.

3.4.2

Basic Operations Of Heaps

Insert operation in a Heap: The Insert operation is used to insert an element into the heap as well as to build the heap from the scratch. Consider the following list of numbers. If a max heap is to be constructed using the list of numbers then that is done as shown.

Figure 3.20: Heap The rst element is placed as the root of the tree. The next element is placed at the end of the present tree. Whenever new element is added at the end of the tree, it is compared with its parent and if it is greater than its parent, then it is exchanged with its parent. The same process is continued till the root or till the new node nds its correct position.

Figure 3.21: Heap Algorithm: INSERT( A[ ], T, k ) N=T N=N+1 A[N] = k While N! = 1 If A[N] A[N/2] N = N/2

3.4. HEAPS Else Break End if End while T=T+1 End INSERT

67

Delete operation in a Heap: The Delete operation always deletes the root element from the heap. The last element of the heap is overwritten in the root node. Now the root node does not satisfy the heap property, hence we need to heapify the entire tree. Hence a procedure called walkdown is applied on the root node, which walks down the root node to its correct position, thus making the tree again a heap.

Figure 3.22: Deletion in Heap

Algorithm: DELETE( A[ ], T, k ) A[1] = A[T] T=T-1 WALKDOWN( A[ ], 1, T ) End DELETE WALKDOWN(A[ ] , I, N) // A is the array used for implementing the heap // N is the number of elements in the heap // I is the position of the node where the walkdown procedure is to be applied. While I ? N/2 L 2I, R 2I + 1 If A[L] A[I] Then ML Else MI End If If A[R] A[M] and R ? N Then MR End If If M ? I Then A[I] A[M]

68 IM Else Return End If End While End WALKDOWN

CHAPTER 3. UNIT-III

3.5
3.5.1

UNIT-V
BASIC TERMINOLOGIES IN GRAPH:

1. Graph: Graph is a non-linear data structure used to represent the network structure. A graph is a collection of nodes(or) vertices and edges. A graph G= (V, E) consists of a set of vertices (v) and set of edges (E). Each edge has a pair (v, w), where v, w ? V Edges are also called arcs. 2. Directed Graph (or) Digraph: If the pair of edges are ordered or directionally oriented, then it is called directed graph or digraph. Example:

Figure 3.23: Directed Graph

3. UnDirected Graph: If the edge in a graph is not directionally oriented, then it is called undirected graph. Example:

Figure 3.24: Undirected Graph

4. Path: It is a sequence of vertices w1, w2..wn such that (wi, wi+1) ? V for 1?i?N. 5. Path length: It is the number of edges present in the path, which is equal to N-1 , where N is the number of vertices.

3.5. UNIT-V 6. Loop path: If the graph contains an edge (v, v) from a vertex to itself, then the path from v to v is called Loop. Example:

69

Figure 3.25: Loop Path

7. Simple path: It is path such that all vertices are distinct, expect that rst and last could be the same. 8. Cycle graph: A cycle in a directed graph is a path of length at least 1 such that w1=wN, then the graph is called cycle graph. (or) If the path in the graph starts and ends with the same vertices is called cycle graph (or) cyclic graph. Eg: In an undirected graph, the path should not be considered as a cycle, because (u, v) and (v, u) are the same edge.

Figure 3.26: Cycle Graph

9. Acyclic graph: A directed graph is said to be a cyclic when there is no cyclic path in it. It is also called DAG (Directed Acyclic graph). 10. Connected graph: An Undirected graph is said to be connected if there is a path from every vertex to every other vertex.

Figure 3.27: Connected Graph 11. Strongly Connected:

70

CHAPTER 3. UNIT-III

In a digraph, if there is a path from every vertex to every other vertex is called strongly connected. Example:

Figure 3.28: Strongly Connected Graph

12. Weakly Connected: A Digraph is said to be weakly connected, when there is no path at least between 2 vertices Here, there is no path from 5 to 4.

Figure 3.29: Weakly Connected Graph

13. Complete Graph: A graph is said to be complete graph in which there is an edge between every pair of vertices. 14. Directed graph / Digraph: The edges between vertices are directionally oriented.

Figure 3.30: Directed Graph(or) Digraph

15. Undirected graph: The edges are not directionally oriented. Note: The directed edge is also called an arcs.

16. Adjacent vertex: In a graph, if there is a directed edge exist between 2 vertices (Vx, Vy), then they are called adjacent vertices.

3.5. UNIT-V

71

Figure 3.31: Undirected Graph 17. Cycle: It is a path, in which starting and ending vertices are the same one (i.e.) the path with will start and end in the same vertices.

Figure 3.32: Cycle

18. Loop: A loop is a special case of a cycle in which a single arc Begins and ends with the same vertex

Figure 3.33: Loop

19. Disjoint: A graph is said to be disjoint, if it is not connected.

20. Degree: The degree of a vertex is the number of arcs or edges incident to it. 21. Indegree: The indegree is the numbers of arcs are entering into the vertex. 22. Outdegree: The outdegree of a vertex is the number of arcs exiting (or leaving) from the vertex. Example:

72

CHAPTER 3. UNIT-III

Figure 3.34: Disjoint

Figure 3.35: Degree Of the Graph Degree of D = 4 Indegree of D is 3 Outdegree of D is 1 TOPOLOGICAL SORT: A Topological sort is an ordering of vertices in a directed acyclic graph, such that if there is a path from Vi to Vj appears after Vi in the ordering. Topological ordering is not possible if the graph has a cycle, since foe two vertices V and W on the cycle, V precedes W and W precedes V. Consider the course available at a university as the vertices of a directed graph, where there is an edge from one course to another, if the rst is a prerequisite for the second. 1. A topological order is then listing of all the courses such that all perquisites for a course appear before it does. 2. Second one is a glossary of technical terms that is ordered. So that no term is used in a denition before it is itself dened. 3. Third one is the author of textbook uses a topological order for the topics in the book. We will now see a simple algorithm to nd a topological ordering. Here rst we will nd any vertex with no incoming edges. We can then print this vertex and remove it, along with its edges, from the graph. Then apply the same strategy to the cost of the graph. To start this, dene the in-degree of a vertex V as the number of edges (u, v). We compute the indegrees of all vertices in the graph. Assuming that the indegree array is initialized and that the graph is read into an adjacency list. Routine for simple Topological sort Pseudo code: Void Topsort (Graph G) Int counter; Vertex v, w;

3.5. UNIT-V

73

Figure 3.36: Degree Of the Graph

For (counter=0; counterNumvertex; counter++) V=FindNewvertexofdegreeZero (); If (v==Notvertex) Error (graph has a cycle); Break; Topnum[v] =counter; For each w adjacent to v Indegree[w]; The function FindNewvertexofDegree zero scans the indegree array looking for a vertex with indegree 0 that has not already been assigned a topological number. It returns not vertex if no such vertex exists, this indicates that the graph has a cycle. Because FindNewvertexofDegreeZero is a simple sequential scan of the indegree array, each will take O ( V) Time. Such v calls, the running time of the algorithm is O (v2).Consider the graph, A cyclic graph Result: Topological ordering can be i) V1 v2 v5 v4 v3 v7 v6 ii)

Figure 3.37: Degree Of the Graph v1 v2 v5 v4 v7 v3 v6 The next routine that the graph is already read into an adjacency list and that the indegrees are computed and placed in an array. For convenient way, the indegree of each vertex in the header cell, assume an array TopNum, in which to place the topological numbering. Routine to perform Topological Sort:

74 Void Topsort (Graph G) Queue Q; int counter = 0; Vertex v, w; Q=CreateQueue (Numvertex) Makeempty (Q); For each vertex V If (Indegree[v] ==0) Enqueue (V, Q); While (! Isempty (Q)) V=Dequeue Q); TopNum[v] =++counter; For each w adjacent to v If ( indegree[w] ==0) Enqueue (w,Q); If (counter! = Numvertex) Error (Graph has a cycle); DisposeQueue (Q);

CHAPTER 3. UNIT-III

The time to perform this algorithm is O (E+V) if adjacency list are used.

BREADTH-FIRST TRAVERSAL: As the name implies, this method traverses the nodes of the graph by searching through the nodes breadthwise. Initially let the rst node of the graph be visited. This node is now considered as node u. Now nd out all the nodes which are adjacent to this node. Let all the adjacent nodes be called as w. Add the node u to a queue. Now every time an adjacent node w is visited, it is added to the queue. One by one all the adjacent nodes w are visited and added to the queue. When all the unvisited adjacent nodes are visited, then the node u is deleted from the queue and hence the next element in the queue now becomes the new node u. The process is repeated on this new node u. This is continued till all the nodes are visited. The Breadth First Traversal (BFT) algorithm calls the BFS algorithm on all the nodes. Algorithm BFT(G, n) Repeat for i = 1 to n Visited[i] = 0 End Repeat Repeat for i = 1 to n If visited[i] = 0 BFS(i) End if End Repeat BFS(v) u=v visited[v] = 1 Repeat while(true) Repeat for all vertices w adjacent from u If visited[w] = 0 Add w to queue Visited[w] = 1 End if

3.5. UNIT-V End Repeat If queue is empty Return End if Delete u from queue End while End BFS

75

76

CHAPTER 3. UNIT-III

Figure 3.38: Breadth First Traversal Now the following diagrams illustrates the BFS on a directed graph.

Figure 3.39: Breadth First Traversal

3.5. UNIT-V SHORTEST PATH ALGORITHM:

77

One of the most common applications in graph is nding the shortest path between two vertices in a network. Here we can nd shortest path for both weighted and unweighted graph. The input is a weighted graph associated with each edge (Vi,Vj) is a cost Ci,j to traverse the arc. The cost n-1 of a path V1,V2,..VN is Ci i + 1. This is referred to as weighted path length. i=1 The unweighted path length is the number of edges of the path, namely N-1 edges. Single-Source Shortest-Path Problem: Given an input a weighted graph, G= (V E), and a distinguished vertex, S, nd the shortest weighted path from S to every other vertex in G. Consider a directed Graph G, The shortest weighted path from V1 to V6 has a cost of 6 and goes from V1

Figure 3.40: Single Source Shortest Path to V4 to V7 to V6. The shortest unweighted path between these vertices is 2. A graph with negative - cost cycle Here, the

Figure 3.41: Single Source Shortest Path path from V5 to V4 is 1, but a shorter path exists by the following the loop V5,V4,V2,V5,V4 which has path (-5). Thus the shortest path between these two points is undened. The shortest path from V1 to V6 is undened. The loop which is undened is called negative- cost cycle. UNWEIGHTED SHORTEST PATH:

Figure 3.42: Single Source Shortest Path

In an above unweighted graph G, some vertex S, this is an input parameter, then to nd the shortest path from S to all other vertices. So path length is the number of edges contained on the path, so there is no weights on the edges. Since all edges has a weight of 1.

78 Consider s=V3, so the shortest path from S to V3 is 0. Step1: Graph after marking the start node in zero edges.

CHAPTER 3. UNIT-III

Figure 3.43: Single Source Shortest Path

Step2: Graph after nding all vertices whose path length from S is 1.

Figure 3.44: Single Source Shortest Path

Step3: Graph with path length 2 from S.

Figure 3.45: Single Source Shortest Path

Step4: nd Shortest path

3.6. MINIMUM SPANNING TREE

79

Figure 3.46: Single Source Shortest Path

3.6

MINIMUM SPANNING TREE

A graph can have many spanning tree. A spanning tree of a graph is just a subgraph that contains all the vertices of the graph.But uses only the sucient edges to form a tree. Spanning tree of the graph do not have cycles. A minimum spanning tree is a spanning tree in which the sum of weight of the edges is minimum. A minimum spanning tree exists if and only if G is connected. The number of edges in the minimum spanning tree is V - 1 .The minimum spanning tree is a tree because it is Acyclic There are two algorithms used for determining the minimum spanning tree of the graph. The minimum spanning tree algorithms are, Kruskals Algorithm Prims Algorithm Both of these algorithm follows greedy technique. Kruskals Algorithm The kruskals algorithm is used for determining minimum spanning tree. Rules: Each vertex of the graph is taken as a one-node tree. A minimum weighted edge is selected to connect two trees together. This iteration continues till all the trees of the forest form a single tree. Prims Algorithm: The Prims algorithm is used for determining the minimum spanning tree. rules: The tree is started with the root. It is connected to the other vertex with minimum weighted edge. This iteration continues till all the vertices are covered in the tree without any cycles. Conditions for selecting the edges: The inclusion of the edges should not form a cycle. The cost of the resulting tree is minimum. Example:

Figure 3.47: Undirected Graph

80 Solution Based On Kruskals Algorithm: Stage1: A forest with seven trees

CHAPTER 3. UNIT-III

Figure 3.48:

Stage2: Minimum weighted edge is selected to connect the vertices. The edge (V1,V4) and (V6,V7) is selected.

Figure 3.49:

Stage3: Next, the minimum weighted edge is selected to connect the vertices. The edge(V1,V2) and (V3,V4) is selected.

Figure 3.50: Stage4: Next, the minimum weighted edge is rejected. Because, the edge (V2,V3) inclusion will form a cycle.

3.6. MINIMUM SPANNING TREE

81

Figure 3.51:

Stage5: Next, the minimum weighted edge is selected to connect the vertices. The edge(V4,V7) is selected. The same cost of the edge(V1,V3) is rejected.Because it inclusion will form a cycle.

Figure 3.52:

Solution Based On the Prims Algorithm:

82

CHAPTER 3. UNIT-III

3.7

Depth First Traversal

In the Depth First Search Traversal, as the name implies the nodes of the graph are traversed by searching through all the nodes by rst going to the depth of the graph. The rst node is visited rst. Let this be node u. Find out all the adjacent nodes of u. Let that be w. Apply the DFS on the rst adjacent node recursively. Since a recursive approach is followed, the nodes are traversed by going to the depth of the graph rst. The DFT algorithm calls the DFS algorithm repeatedly for all the nodes in the graph. Algorithm DFT(G, n) Repeat for i = 1 to n Visited[i] = 0 End Repeat Repeat for i = 1 to n If visited[i] = 0 DFS(i) End if End Repeat DFS(v) Visited[v] = 1 Repeat for each vertex w adjacent from v If visited[w] = 0 DFS(w) End if End for

Figure 3.53: Depth First Traversal

3.8

BI CONNECTIVITY

A bi connected graph is a graph is a connected graph that is not broken into disconnected pieces by deleting any single vertex (and incident edges) . A bi connected graph remains connected after removing one(any) vertex (or) edges. In other words, a bi connected graph is non separable. meaning if any edge were to be removed ,the graph will remain connected. A bi connected undirected graph G is a set of vertices V so that every vertex has at least two connecting edges , connecting to two separate vertices other than itself.

3.8. BI CONNECTIVITY

83

A bi connected strongly connected directed graph G is a set of vertices V so that every vertex has at least two in degree vertices and at least tow out degree vertices. (i.e) there are at least two independent paths from any vertex to any other vertex. A non-bi connected graph is a graph in which a removal of any vertex disconnects the graph. A vertex whose removal disconnects the connected graph is said to be articulation point.The articulation point is not responsible for non-bi connectivity. Any graph containing a node of degree 1 cannot be bi connected. A graph with no articulation vertices is called a bi connected graph ,block or nonseparable graph. A vertex v in a graph G is called an articulation point if its removal from G would cause the graph to be disconnected. Such vertices would be considered critical in applications like networks where articulation points are the only means of communication between dierent portions of the network. A depth rst search can be used to nd all of a graphs articulation points. Properties Of Bi connected Graph:

There are two disjoint paths between ant two vertices. There is a cycle through any two vertices. Bi connected Component A bi connected component of a undirected graph is a maximal bi connected subgraph that is a bi connected subgraph not contained in any larger bi connected subgraph. Bi connected component is a maximal connected subgraph H of a graph G. Finding the Bi connected Components: By using depth rst spanning tree of a connected undirected graph, we can nd the bi connected components of a connected graph. The depth rst number(dfn) outside the vertices in the gures gives the DFS visit sequence. If u is an ancestor of v then dfn(u)dfn(v)

Das könnte Ihnen auch gefallen