Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
DATA STRUCTURES USING C
Revision 4.0
1 December, 2014
L. V. NARASIMHA PRASAD
Professor
Department of Computer Science and Engineering
E. KRISHNA RAO PATRO
Associate Professor
Department of Computer Science and Engineering
INSTITUTE OF AERONAUTICAL ENGINEERING
DUNDIGAL – 500 043, HYDERABAD
20142015
CONTENTS
CHAPTER 1 BASIC CONCEPTS
1.1
1.2
1.3.
1.4.
1.5.
1.6.
1.7.
1.8.
1.9.
1.10.
1.11.
Introduction to Data Structures
Data structures: organizations of data
Abstract Data Type (ADT)
Selecting a data structure to match the operation
Algorithm
Practical Algorithm design issues
Performance of a program
Classification of Algorithms
Complexity of Algorithms
Rate of Growth
Analyzing Algorithms
Exercises
Multiple Choice Questions
CHAPTER 2 RECURSION
2.1.
2.2.
2.3.
2.4.
2.5.
2.6.
2.7.
2.8.
Introduction to Recursion
Differences between recursion and iteration
Factorial of a given number
The Towers of Hanoi
Fibonacci Sequence Problem
Program using recursion to calculate the NCR of a given number
Program to calculate the least common multiple of a given number
Program to calculate the greatest common divisor
Exercises
Multiple Choice Questions
CHAPTER 3 LINKED LISTS
3.1.
3.2.
3.3.
Linked List Concepts
Types of Linked Lists
Single Linked List
3.3.1. Source Code for the Implementation of Single Linked List
3.4.
Using a header node
3.5.
Array based linked lists
3.6.
Double Linked List
3.6.1. A Complete Source Code for the Implementation of Double Linked List
3.7.
Circular Single Linked List
3.7.1. Source Code for Circular Single Linked List
3.8.
Circular Double Linked List
3.8.1. Source Code for Circular Double Linked List
3.9.
Comparison of Linked List Variations
3.10. Polynomials
3.10.1. Source code for polynomial creation with help of linked list
3.10.2. Addition of Polynomials
3.10.3. Source code for polynomial addition with help of linked list:
Exercise
Multiple Choice Questions
I
CHAPTER 4 STACK AND QUEUE
4.1.
Stack
4.1.1. Representation of Stack
4.1.2. Program to demonstrate a stack, using array
4.1.3. Program to demonstrate a stack, using linked list
4.2.
Algebraic Expressions
4.3.
Converting expressions using Stack
4.3.1. Conversion from infix to postfix
4.3.2. Program to convert an infix to postfix expression
4.3.3. Conversion from infix to prefix
4.3.4. Program to convert an infix to prefix expression
4.3.5. Conversion from postfix to infix
4.3.6. Program to convert postfix to infix expression
4.3.7. Conversion from postfix to prefix
4.3.8. Program to convert postfix to prefix expression
4.3.9. Conversion from prefix to infix
4.3.10. Program to convert prefix to infix expression
4.3.11. Conversion from prefix to postfix
4.3.12. Program to convert prefix to postfix expression
4.4.
Evaluation of postfix expression
4.5.
Applications of stacks
4.6.
Queue
4.6.1. Representation of Queue
4.6.2. Program to demonstrate a Queue using array
4.6.3. Program to demonstrate a Queue using linked list
4.7.
Applications of Queue
4.8.
Circular Queue
4.8.1. Representation of Circular Queue
4.9.
Deque
4.10. Priority Queue
Exercises
Multiple Choice Questions
CHAPTER 5 BINARY TREES
5.1.
5.2.
5.3.
5.4.
5.5.
5.6.
5.7.
5.8.
5.9.
Trees
Binary Tree
Binary Tree Traversal Techniques
5.3.1. Recursive Traversal Algorithms
5.3.2. Building Binary Tree from Traversal Pairs
5.3.3. Binary Tree Creation and Traversal Using Arrays
5.3.4. Binary Tree Creation and Traversal Using Pointers
5.3.5. Non Recursive Traversal Algorithms
Expression Trees
5.4.1. Converting expressions with expression trees
Threaded Binary Tree
Binary Search Tree
General Trees (mary tree)
5.7.1. Converting a mary tree (general tree) to a binary tree
Search and Traversal Techniques for mary trees
5.8.1. Depth first search
5.8.2. Breadth first search
Sparse Matrices
Exercises
Multiple Choice Questions
II
CHAPTER 6 GRAPHS
6.1.
6.2.
6.3.
6.4.
6.5.
Introduction to Graphs
Representation of Graphs
Minimum Spanning Tree
6.3.1. Kruskal’s Algorithm
6.3.2. Prim’s Algorithm
Reachability Matrix
Traversing a Graph
6.5.1. Breadth first search and traversal
6.5.2. Depth first search and traversal
Exercises
Multiple Choice Questions
CHAPTER 7 SEARCHING AND SORTING
7.1.
7.2.
7.3.
7.4.
7.5.
7.6.
7.7.
7.8.
Linear Search
7.1.1. A nonrecursive program for Linear Search
7.1.1. A Recursive program for linear search
Binary Search
7.1.2. A nonrecursive program for binary search
7.1.3. A recursive program for binary search
Bubble Sort
7.3.1. Program for Bubble Sort
Selection Sort
7.4.1 Nonrecursive Program for selection sort
7.4.2. Recursive Program for selection sort
Quick Sort
7.5.1. Recursive program for Quick Sort
Priority Queue and Heap and Heap Sort
7.6.2. Max and Min Heap data structures
7.6.2. Representation of Heap Tree
7.6.3. Operations on heap tree
7.6.4. Merging two heap trees
7.6.5. Application of heap tree
Heap Sort
7.7.1. Program for Heap Sort
Priority queue implementation using heap tree
Exercises
Multiple Choice Questions
References and Selected Readings
Index
III
and choosing an algorithm affects the data structures we use. and the term algorithm is used to describe the way data is processed.Chapter 1 Basic Concepts The term data structure is used to describe the way data is stored. 1. Primitive Data Structures are the basic data structures that directly operate upon the machine instructions. lists and files come under this category. Graphs are nothing but trees with certain restrictions removed. Nonprimitive data structures are more complicated data structures and are derived from primitive data structures. data structure is represented as: Algorithm + Data structure = Program A data structure is said to be linear if its elements form a sequence or a linear list. Arrays. They have different representations on different computers. In other words. Figure 1. Choosing a data structure affects the kind of algorithm you might use. each of which has a clear meaning and can be performed with a finite amount of effort in a finite length of time.1. data items appear at various levels. character constants. Introduction to Data Structures: Data structure is a representation of logical relationship existing between individual elements of data. floating point numbers. a data structure defines a way of organizing all data items that considers not only the elements stored but also their relationship to each other. Data structures and algorithms are interrelated. Data structures are divided into two types: • • Primitive data structures. stacks. Nonprimitive data structures. The linear data structures like an array. string constants and pointers come under this category. Lecture Notes 1 Dept. No matter what the input values may be. Integers. The term data structure is used to describe the way data is stored. They emphasize on grouping same or different data items with relationship between each data item. of Information Technology . Therefore. queues and linked lists organize data in linear order. A data structure is said to be non linear if its elements form a hierarchical classification where.1 shows the classification of data structures. an algorithm terminates after executing a finite number of instructions. Trees and Graphs are widely used nonlinear data structures. An Algorithm is a finite sequence of instructions. To develop a program of an algorithm we should select an appropriate data structure for that algorithm. Tree and graph structures represents hierarchial relationship between individual data elements.
items in a noncontiguous structure and scattered in memory. In contiguous structures. and thus has the same size. No matte how complex your data structures are they can be broken down into two fundamental types: • Contiguous • NonContiguous.3(b) shows a simple structure consisting of a person’s name and age.2 Contiguous and Noncontiguous structures compared Contiguous structures: Contiguous structures can be broken drawn further into two kinds: those that contain data items of all the same size. Data structures: Organization of data The collection of data you work with in a program have some kind of structure or organization. terms of data are kept together in memory (either RAM or in a file).L i n e ar L i st s Queues Gr a p h s T re e s F i g ur e 1. In contrast. In a struct. figure 1. A linked list is an example of a noncontiguous data structure.Pr i mi t iv e Da t a St r uc t ur e s Pr i mi t iv e Da t a St r uc t ur e s I nt e g er F l o at C h ar P o i nt er s Arr ay s L i st s L i n e ar L i st s St ac k s File s No n. In an array. 1 2 3 1 (a) Contiguous 2 3 (b) noncontiguous Figure 1. An array is an example of a contiguous structure. but we linked to each other in some way. Here. and those where the size may differ.3(a) shows an example of an array of numbers. Lecture Notes 2 Dept.2 below illustrates the difference between contiguous and noncontiguous structures. the nodes of the list are linked together using pointers stored in each node.Da t a St r uc t ur e s No n. Since each element in the array is located next to one or two other elements. of Information Technology . elements may be of different data types and thus may have different sizes.2. Figure 1. Figure 1. The second kind of contiguous structure is called structure. Figure 1. 1. each element is of the same type.2 shows example of each kind. The first kind is called the array. C l a s s if ic at i o n of Da t a St r uc t ur e s 1.
onedimension type of noncontiguous structure. char name[20]. including the noncontiguous forms.3 Examples of contiguous structures. (a) Array 21 (b) struct “bill the student” Figure 1. 1 2 struct cust_data { int age. Here.4(c) is an example of a graph. a person’s age can be represented with a simple integer that occupies two bytes of memory. Figure 1. The simplest kind of noncontiguous structure is linked list. Examples of noncontiguous structures Lecture Notes 3 Dept. where each node can point to one or more other nodes in the collection. 2. 3 cust_data bill= {21. A tree such as shown in figure 1. called a graph has no such restrictions.4(b) is an example of a twodimensional noncontiguous structure. A B C A B (a) Linked List C D A E B G C F (b) Tree D E F (c) graph G Figure 1. A linked list represents a linear. In a tree each node has only one link that leads into the node and links can only go down the tree.For example. The most general type of noncontiguous structure. there is the notion of up and down and left and right. where there is only the notation of backwards and forwards. may require many bytes and may even be of varying length. But his or her name. “bill the student”}. int arr[3] = {1.4. 3}. represented as a string of characters. Couples with the atomic types (that is. arrays and structs provide all the “mortar” you need to built more exotic form of data structure. Noncontiguous structures: Noncontiguous structures are implemented as a collection of dataitems. called nodes. the single dataitem builtin types such as integer. }. float and pointers). of Information Technology .
leads to the notion of an abstract data type. So we created what is known Lecture Notes 4 Dept. we haven’t specified have items are stored on the stack. D[i] holds the data for node i and p[i] holds the index to the node previous to i. For example. A double linked list via a hybrid data structure The array D contains the data for the list.arrays and structures – can also be implemented noncontiguously. The abstract notion of a data structure is defined in terms of the operations we plan to perform on the data. For example. For instance. Abstract Data Type (ADT): The design of a data structure involves more than just its organization. N[i] holds the index to the next node in the list. Then one part contiguous and another part noncontiguous. We call these operations. Like wise. noncontiguous structures – including lists.Hybrid structures: If two basic types of structures are mixed then it is a hybrid form. possibly stored a past from each other in memory. 1. For example. figure 1. We have only specified the valid operations that can be performed. we may have to write the same code over and over again. The notion of a data structure in the abstract needs to be treated differently from what ever is used to implement the structure.5. That is. Considering both the organization of data and the expected operations on the data. how the data will be interpreted actually. pushing and popping.3. or how the items are pushed and popped. You also need to plan for the way the data will be accessed and processed – that is.5 shows how to implement a double– linked list using three parallel arrays. whereas the array P and N hold the previous and next “pointers’’. of Information Technology . where may or may not reside at position i–1. we wrote the code to read the physical file device. tree and graphs – can be implemented either contiguously or non. In this definition. a stack is a typical abstract data type. if we want to read a file. Items stored in a stack can only be added and removed in certain order – the last item added is the first item removed. An abstract data type in a theoretical construct that consists of data as well as the operations to be performed on the data while hiding implementation. The pointers are actually nothing more than indexes into the D array.contiguously like wise. the structures that are normally treated as contiguously . A List Head B C (a) Conceptual Structure D P N 1 A 3 4 2 B 4 0 3 C 0 1 4 D 1 2 (b) Hybrid Implementation Figure 1.
an abstract data type (such as stack) has to be implemented and this is where data structure comes into ply. for integer elements. the code to read from a keyboard is an ADT. In this case. we just modify the pointers in each node. however we can separate the logical ordering from the physical ordering and thus change one without affecting the other. such as an array the logical ordering (the ordering that we wish to interpret our elements to have) is the same as the physical ordering (the ordering that the elements actually have in memory). The code for this is as follows: void delete (int *seg. where one of the main operations is delete an object from the middle of the sequence. This shifting involves data movement that. which is too costly. 1. we might choose the simple data structure of an array to represent the stack. Selecting a data structure to match the operation: The most important process in designing a problem involves choosing which data structure to use. The problem is that. instead. However.4. if we store our collection of elements using a double–linked list (with previous and next pointers). As another example. in a contiguous structure. the overhead for moving data becomes high. For instance. of Information Technology . int posn) //delete the item at posn from a list of elements. { int i = posn. To be made useful. It has a data structure. and then define the appropriate indexing operations to perform pushing and popping. n. } This function shifts towards the front all elements that follow the element at position posn. { if (n) { int i=posn. For example. int posn) // delete the item at position from an array of n elements. i++. The choice depends greatly on the type of operations you wish to perform. The code using double linked list is as follows: void delete (node * beg. and lots of them. } } return.today as an ADT. node *q = beg. we can do the deletion without moving the elements. while (i < n) { seq[i] = seg[i+1]. Suppose we have an application that uses a sequence of objects. int &n. If we choose noncontiguous representation. We wrote the code to read a file and placed it in a library for a programmer to use. suppose the array stores larger objects. character and set of operations that can be used to read that data structure. while (i && q) { Lecture Notes 5 Dept.
Our linked lists yield faster deletions. No matter what the input values may be. Algorithm An algorithm is a finite sequence of instructions. so detach P by making previous and next nodes point to each other */ node *p = q > prev. Output: at least one quantity is produced.i. but they take up more space because they require two extra pointers per element. if (n) n > prev = P. But is that always true? There are trade offs. which are externally supplied. } return. each of which has a clear meaning and can be performed with a finite amount of effort in a finite length of time. an algorithm terminates after executing a finite number of instructions. the deletion using linked lists will often be faster than when arrays are used. 1. q = q Æ next. of Information Technology . node *n = q > next. It may seem that linked lists are superior to arrays. In addition every algorithm must satisfy the following criteria: Input: there are zero or more quantities.5.6 Detaching a node from a list Since very little data is moved during this process. } if (q) { /* not at end of list. if (p) p > next = n. Lecture Notes 6 Dept. and can be accomplished with some pointer manipulation as illustrated in figure below: A X 200 100 Initial List A C 300 X A Figure 1. } The process of detecting a node from a list is independent of the type of data stored in the node.
The time complexity of a program is the amount of computer time it needs to run to completion. Practical Algorithm design issues: Choosing an efficient algorithm or data structure is just one part of the design process. Space Complexity: The space complexity of a program is the amount of memory it needs to run to completion. In formal computer science. A program that runs faster is a better program. Try to save space (Space complexity). A program does not necessarily satisfy the fourth condition. There are three basic design goals that we should strive for in a program: 1. which never terminates (except for system crashes) but continues in a wait loop until more jobs are entered.Definiteness: each instruction must be clear and unambiguous. but it must also be feasible. and a program. Effectiveness: every instruction must be sufficiently basic that it can in principle be carried out by a person using only pencil and paper. One important example of such a program for a computer is its operating system. Try to have face. then for all cases the algorithm will terminate after a finite number of steps. of Information Technology . One is analytical. We represent an algorithm using pseudo language that is a combination of the constructs of a programming language together with informal English statements. 3. Next. We use two approaches to determine the performance of a program. Try to save time (Time complexity). We want to “save face” by preventing the program from locking up or generating reams of garbled data. Finiteness: if we trace out the instructions of an algorithm. The space need by a program has the following components: Lecture Notes 7 Dept. a program that saves space over a competing program is considered desirable. Time Complexity: The time needed by an algorithm expressed as a function of the size of a problem is called the TIME COMPLEXITY of the algorithm. 1. while in performance measurement we conduct experiments. so saving time is an obvious goal. Like wise. 1. It is not enough that each operation be definite. will look at some design issues that are broader in scope. In performance analysis we use analytical methods. 2.6. It is the asymptotic complexity of an algorithm. one distinguishes between an algorithm. Performance of a program: The performance of a program is the amount of computer memory and time needed to run a program. which ultimately determines the size of problems that can be solved by the algorithm. The limiting behavior of the complexity as size increases is called the asymptotic time complexity. and the other experimental.7.
Space needed by dynamically allocated objects such as arrays and class instances. an algorithm that process triples of data items (perhaps in a triple– nested loop) has a cubic running time and is practical for use only on small problems. Data space has two components: • • Space needed by constants and simple variables in program. log n is a doubled whenever n doubles. 1. Classification of Algorithms If ‘n’ is the number of data items to be processed or degree of polynomial or the size of the file to be sorted or searched or the number of nodes in a graph etc. Instruction Space: The amount of instructions space that is needed depends on factors such as: • The compiler used to complete the program into machine code. Environment stack space: The environment stack is used to save information needed to resume execution of partially completed functions. Quadratic running times typically arise in algorithms that process all pairs of data items (perhaps in a double nested loop) whenever n doubles. cutting the size by some constant fraction. we say that its running time is a constant. When n is a million. If all the instructions of a program have this property. • The compiler options in effect at the time of compilation • The target computer. This is the optimal situation for an algorithm that must process n inputs. Lecture Notes 8 Dept. When n doubles. the running time increases eight fold. log n increases by a constant. Whenever n doubles. n. of Information Technology . Data space: Data space is the space needed to store all constant and variable values. This running time commonly occurs in programs that solve a big problem by transforming it into a smaller problem. solving them independently. the running time squares. 2n Few algorithms with exponential running time are likely to be appropriate for practical use. n3 Similarly. Whenever n doubles.Instruction space: Instruction space is the space needed to store the compiled version of the program instructions. the program gets slightly slower as n grows. but log n does not double until n increases to n2.. n2 When the running time of an algorithm is quadratic.8. Log n When the running time of a program is logarithmic. it is practical for use only on relatively small problems. the running time increases four fold. such algorithms arise naturally as “brute–force” solutions to problems. n When the running time of a program is linear. it is generally the case that a small amount of processing is done on each input element. log n This running time arises for algorithms but solve a problem by breaking it up into smaller subproblems. the running time more than doubles. and then combining the solutions. 1 Next instructions of most programs are executed once or at most only a few times.
Some Examples: 2n2 2n2 2n2 2n2 + + + + 5n 5n 5n 5n – – – – 6 6 6 6 = = = ≠ O(2n) O(n3) O(n2) O(n) 2n2 2n2 2n2 2n2 + + + + 5n 5n 5n 5n – – – – 6 6 6 6 ≠ ≠ = ≠ Θ(2n) Θ(n3) Θ(n2) Θ(n) 2n2 2n2 2n2 2n2 + + + + 5n 5n 5n 5n – – – – 6 6 6 6 ≠ ≠ = = Ω(2n) Ω(n3) Ω(n2) Ω(n) 2n2 2n2 2n2 2n2 + + + + 5n 5n 5n 5n – – – – 6 6 6 6 = = ≠ ≠ o(2n) o(n3) o(n2) o(n) Lecture Notes 9 Dept. Algorithms can be evaluated by a variety of criteria. The complexity function f(n) for certain cases are: 1. the storage space required by an algorithm is simply a multiple of the data size ‘n’. T(n) = Ω(g(n)) (pronounced omega). Rate of Growth Big–Oh (O). 1. Worst Case : The maximum value of f(n) for any key possible input. The field of computer science. called the size of the problem. Best Case : The minimum possible value of f(n) is called the best case. says that the growth rate of T(n) is less than or equal (<) that of f(n) 2. 2. says that the growth rate of T(n) is less than the growth rate of p(n) [if T(n) = O(p(n)) and T(n) ≠ Θ (p(n))].9. Complexity shall refer to the running time of the algorithm. Complexity of Algorithms The complexity of an algorithm M is the function f(n) which gives the running time and/or storage space requirement of the algorithm in terms of the size ‘n’ of the input data. of Information Technology . says that the growth rate of T(n) is greater than or equal to (>) that of g(n) 3. Big–Theta (Θ) and Little–Oh 1. depends not only on the size ‘n’ of the input data but also on the particular data. gives the running time of an algorithm. says that the growth rate of T(n) equals (=) the growth rate of h(n) [if T(n) = O(h(n)) and T(n) = Ω (h(n)] 4. Mostly. T(n) = o(p(n)) (pronounced little oh). Big–Omega (Ω). Average Case : The expected value of f(n). (pronounced order of or big oh). T(n) = O(f(n)). The function f(n). is known as analysis of algorithms. Most often we shall be interested in the rate of growth of the time or space required to solve larger and larger instances of a problem. T(n) = Θ(h(n)) (pronounced theta).10. which studies efficiency of algorithms. which is a measure of the quantity of input data. We will associate with the problem an integer.1. 3.
O(n2). O(2n). Clearly the complexity f(n) of M increases as n increases. O(n. O(log2 n).1. n2. of Information Technology .No log n n n. We will also throw away low–order terms while computing a Big–Oh running time. Analyzing Algorithms Suppose ‘M’ is an algorithm. the answer provided is a guarantee that the program will terminate within a certain time period. log n n2 n3 2n 1 0 1 1 1 1 2 2 1 2 2 4 8 4 3 2 4 8 16 64 16 4 3 8 24 64 512 256 5 4 16 64 256 4096 65536 Graph of log n. n3. Lecture Notes 10 Dept. It is usually the rate of increase of f(n) we want to examine. Thus we throw away leading constants. log2 n). n log n. n! and nn O(log n) does not depend on the base of the logarithm. n. the convention will not have any particular units of time. To simplify the analysis. O(n3). and suppose ‘n’ is the size of the input data. Since BigOh is an upper bound. This is usually done by comparing f(n) with some standard functions. The most common computing times are: O(1).11. but never later. The program may stop earlier than this. O(n). 2n. n! and nn Numerical Comparison of Different Algorithms The execution time for six of the typical functions is given below: S.
Then might not 5n3 program better than 100n2 program? As the programs can be evaluated by comparing their running time functions. Define worst case of an algorithm. State the properties of algorithms. Define average case of an algorithm. we would indeed prefer the program whose running time was O(n3) However. if the first program takes 100n2 milliseconds. of Information Technology . State the various steps in developing algorithms? 3. 10. with constants by proportionality neglected. 5 n3/100 n2 = n/20 for inputs n < 20. the O(n3) program will take significantly more time than the O(n2) program. 2. Therefore. Define best case of an algorithm. the order of complexity for: • • • • Linear search is O(n) Binary search is O(log n) Bubble sort is O(n2) Quick sort is O(n log n) For example. if the program is to be run mainly on inputs of small size. State the various methods to estimate the efficiency of an algorithm. Define time complexity of an algorithm? 7. 4. 6. as ‘n’ gets large. Lecture Notes 11 Dept.One way to compare the function f(n) with these standard function is to use the functional ‘O’ notation. For example. So it is always better to prefer a program whose running time with the lower growth rate. Then. which is n/20. Exercises 1. While the second taken 5n3 milliseconds. 9. Define algorithm. f(n) = O(g(n)) Which is read as “f(n) is of order g(n)”. 8. 5n3 program be better than the 100n2 program. Thus. the program with running time 5n3 will be faster those the one with running time 100 n2. as the size of the input increases. Define efficiency of an algorithm? 5. Mention the various spaces utilized by a program. the ratio of the running times. So. suppose f(n) and g(n) are functions defined on the positive integers with the property that f(n) is bounded by some multiple g(n) for almost all ‘n’. gets arbitrarily larger. The low growth rate function’s such as O(n) or O(n log n) are always better.
A. Cannot be defined B. Time Complexity D. Algorithm B. _____ is a stepbystep recipe for solving an instance of problem. Define space complexity of an algorithm. Pseudocode D. Dynamic Programming C. Dynamic Programming ______ is used to define the worstcase running time of an algorithm. A. Analysis [ A ] 2. ______ of an algorithm is the amount of time (or the number of steps) needed by a program to complete its task. A. Analysis Lecture Notes 12 Dept. [ C ] [ A ] A. Natural Language C.11. ______ is used to describe the algorithm. 12. Divide and Conquer D. of Information Technology . B. None [ C ] 3. Complexity C. BigOh notation B. A. ______ of a program is the amount of memory used at once by the algorithm until it completes its execution. in less formal language. Space Complexity 5. Space Complexity B. Cannot be defined C. Time Complexity [ D ] 4. State the different memory spaces occupied by an algorithm. Divide and Conquer C. Multiple Choice Questions 1. Complexity D. Pseudocode D.
Many programmers prefer recursion through simpler alternatives are available. num. Introduction to Recursion: A function is recursive if a statement in the body of the function calls itself. It is because recursion is elegant to use through it is costly in terms of time and space. For a computer language to be recursive. scanf (“%d”. fact).h> int factorial (int). printf ("\n Factorial of %d =%5d\n". of Information Technology . else result = n * factorial (n1). result = 1. main() { int num. But using it is one thing and getting involved with it is another. a function must be able to call itself. &num). let us consider the function factr() shown below. } int factorial (int n) { int result. if (n == 0) Lecture Notes 13 Dept.Chapter 2 Recursion Recursion is deceptively simple in statement but exceptionally complicated in implementation. fact. In this unit we will look at “recursion” as a programmer who not only loves it but also wants to understand it! With a bit of involvement it is going to be an interesting reading for you. } return (result). which computers the factorial of an integer. Recursive procedures work fine in many problems. #include <stdio. if (n == 0) return (1). printf (“Enter a positive integer value: "). For example. A nonrecursive or iterative version for finding the factorial is as follows: factorial (int n) { int i. fact = factorial (num).1. 2. Recursion is the process of defining something in terms of itself.
Recursion terminates when a base case is recognized.return (result). When a function calls itself. Iteration keeps modifying the counter until the loop continuation condition fails. Iteration normally occurs within a loop so the extra memory assigned is omitted. Recursion causes another copy of the function and hence a considerable memory space’s occupied. The recursive definition is: n = 0. Differences between recursion and iteration: • • • Both involve repetition. else { for (i=1. you must have a exit condition somewhere to force the function to return without the recursive call being executed. It reduces the processor’s operating time. i++) result = result * i. or stack overflow.3. 2.2. A recursive call does not make a new copy of the function. Recursion achieves repetition through repeated function calls. the recursive function will recurse forever until you run out of stack space and indicate error about lack of memory. Iteration Recursion Iteration explicitly user a repetition structure. } return (result). new local variables and parameters are allocated storage on the stack and the function code is executed with these new variables from the start. n ! = n * (n . If you do not have an exit condition. 5). Factorial of a given number: The operation of recursive factorial function is as follows: Start out with some natural number N (in our example. i<=n. Both can occur infinitely. Recursion keeps producing simple versions of the original problem until the base case is reached. 0 ! = 1 n > 0. 2. the old local variables and parameters are removed from the stack and execution resumes at the point of the function call inside the function. It increases the processor’s operating time. As each recursive call returns. Only the arguments and variables are new. of Information Technology . When writing recursive functions. } The operation of the nonrecursive version is clear as it uses a loop starting at 1 and ending at the target value and progressively multiplies each number by the moving product.1) ! Lecture Notes Base Case Recursive Case 14 Dept. Both involve a termination test. Iteration terminates when the loop continuation.
with N = 3. FUNCTION: Does N = 0? No Function Return Value = 1 * factorial (0) At this time. with N = 0. All recursive functions must have an exit condition. FUNCTION: Does N = 0? No Function Return Value = 2 * factorial (1) At this time. say.Recursion Factorials: 5! =5 * 4! = 5 *___ = ____ factr(5) = 5 * factr(4) = __ 4! = 4 *3! = 4 *___ = ___ factr(4) = 4 * factr(3) = __ 3! = 3 * 2! = 3 * ___ = ___ 2! = 2 * 1! = 2 * ___ = ___ factr(3) = 3 * factr(2) = __ factr(2) = 2 * factr(1) = __ 1! = 1 * 0! = 1 * __ = __ factr(1) = 1 * factr(0) = __ 0! = 1 factr(0) = __ 5! = 5*4! = 5*4*3! = 5*4*3*2! = 5*4*3*2*1! = 5*4*3*2*1*0! = 5*4*3*2*1*1 =120 We define 0! to equal 1. the function factorial is called again. Tracing of the flow of the factorial () function: When the factorial function is first called with. of Information Technology . FUNCTION: Does N = 0? No Function Return Value = 4 * factorial (3) At this time. and we define factorial N (where N > 0). FUNCTION: Does N = 0? Yes Function Return Value = 1 Lecture Notes 15 Dept. with N = 4. to be N * factorial (N1). N = 5. that is a state when it does not recurse upon itself. here is what happens: FUNCTION: Does N = 0? No Function Return Value = 5 * factorial (4) At this time. the function factorial is called again. FUNCTION: Does N = 0? No Function Return Value = 3 * factorial (2) At this time. the function factorial is called again. with N = 1. Our exit condition in this example is when N = 0. with N = 2. the function factorial is called again. the function factorial is called again.
11. or 120 was returned. at no time can a larger disk be placed on a smaller disk. 3. So. 4. T o w er 1 T o w er 2 T o w er 3 F i g. The objective of the game is to move all the disks in tower 1 to entire tower 3 using tower 2. A larger disk cannot be placed on a smaller disk. disk 1 has diameter 1 (in some unit of measure). all function level calls above still exist! So. the factorial function was called six times. 3.11. The next higher function call. or 2 was returned.2. Only the top disc on any tower can be moved to any other tower. illustrates the initial setup of towers of Hanoi. That is. The disks are numbered from 1 to 3. I n it i a l s et u p of T o w er s of Ha n o i Lecture Notes 16 Dept. or 1. let n is 3. 4. 1. 5. illustrates the final setup of towers of Hanoi.1. You just keep working up the chain. 3. and 3. The figure 3. The Towers of Hanoi: In the game of Towers of Hanoi. 6.4. At any function level call. of Information Technology . and disk 3 has diameter 3. Figure 3. When When When When N N N N = = = = 2. the function call where N = 1 returns 1*1. So. once the final call returns 0. or 6 was returned.Now. 1 1. and without loss of generality we may assume that the diameter of each disk is the same as its number. The game starts with n disks on tower A. 2 3 4 5 * * * * 1. returns 2 * 1 (1. All three disks start on tower A in the order 1. For simplicity. And since N = 5 was the first function call (hence the last one to be recalled). 2. 2. 24. when we have N = 2. the value 120 is returned. there are three towers labeled 1. or 24 was returned. 2. disk 2 has diameter 2. the function instances where N = 3. where N = 2. That is. we have to trace our way back up! See. because that's what the function call where N = 1 returned). the function call where N = 1 gets retraced first. The rules to be followed in moving the disks from tower 1 tower 3 using tower 2 are as follows: • • • Only one disk can be moved at a time. 2. and 5 are still waiting for their return values.
&n). n. a. printf ("\n%5d: Move disk 1 from %s to %s". char *b.h> void towers_of_hanoi (int n. c). printf ("\n%5d: Move disk %d from %s to %s". 2. a. a. return. "Tower 3"). This can be achieved by using the remaining two towers. printf("Enter number of discs: "). char *b. char *a. return. b. since the disk placed on tower 3 is the largest disk and continue the same operation to place the entire disks in tower 3 in order. a. towers_of_hanoi (n. F i n a l s et u p of T o w er s of Ha n o i The towers of Hanoi problem can be easily implemented using recursion. 1 1. c. The program that uses recursion to produce a list of moves that shows how to accomplish the task of transferring the n disks from tower 1 to tower 3 is as follows: #include <stdio. b). char *a. } else { towers_of_hanoi (n1. c).T o w er 1 T o w er 2 T o w er 3 F i g 3. ++cnt. towers_of_hanoi (n1. We can also use tower 3 to place any disk on it. int cnt=0. To move the largest disk to the bottom of tower 3. cnt. getch(). scanf("%d". c). char *c). } void towers_of_hanoi (int n. of Information Technology . "Tower 2". we move the remaining n – 1 disks to tower 2 and then move the largest disk to tower 3. char *c) { if (n == 1) { ++cnt. "Tower 1". } } Lecture Notes 17 Dept. int main (void) { int n.h> #include <conio. Now we have the remaining n – 1 disks to be moved to tower 3. cnt.
7: Move disk 1 from tower 1 to tower 2. . . 2. 4: Move disk 3 from tower 1 to tower 3. of Information Technology . 9: Move disk 1 from tower 2 to tower 3. The sequence of Fibonacci integers is given below: 0 1 1 2 3 5 8 13 21 . 15: Move disk 1 from tower 2 to tower 3. RUN 2: Enter the number of discs: 4 1: Move disk 1 from tower 1 to tower 2. . 2: Move disk 2 from tower 1 to tower 2. . . 14: Move disk 2 from tower 1 to tower 3. third number in the sequence is 0 + 1 = 1. 11: Move disk 1 from tower 3 to tower 1. 3: Move disk 1 from tower 2 to tower 3. 8: Move disk 4 from tower 1 to tower 3. 6: Move disk 2 from tower 3 to tower 2. Lecture Notes 18 Dept. Fibonacci Sequence Problem: A Fibonacci sequence starts with the integers 0 and 1. 7: Move disk 1 from tower 1 to tower 3. 4: Move disk 3 from tower 1 to tower 2. 2: Move disk 2 from tower 1 to tower 3. . 12: Move disk 3 from tower 2 to tower 3. 5: Move disk 1 from tower 3 to tower 1. 6: Move disk 2 from tower 2 to tower 3. . 13: Move disk 1 from tower 1 to tower 2.Output of the program: RUN 1: Enter the number of discs: 3 1: Move disk 1 from tower 1 to tower 3. 5: Move disk 1 from tower 2 to tower 1. 10: Move disk 2 from tower 2 to tower 1. fifth number is 1 + 2 = 3 and so on. .5. Successive elements in this sequence are obtained by summing the preceding two elements in the sequence. For example. 3: Move disk 1 from tower 3 to tower 2. fourth number is 1 + 1= 2.
} Output: fib(5) is 5 Lecture Notes 19 Dept. printf (“=nfib(5) is %d”. A recursive function to compute the Fibonacci number in the nth position is given below: main() { } fib(n) int n.A recursive definition for the Fibonacci sequence of integers may be defined as follows: Fib (n) = n if n = 0 or n = 1 Fib (n) = fib (n1) + fib (n2) for n >=2 We will now use the definition to compute fib(5): fib(5) = fib(4) + fib(3) fib(3) + fib(2) + fib(3) fib(2) + fib(1) + fib(2) + fib(3) fib(1) + fib(0) + fib(1) + fib(2) + fib(3) 1 + 0 + 1 + fib(1) + fib(0) + fib(3) 1 + 0 + 1 + 1 + 0 + fib(2) + fib(1) 1 + 0 + 1 + 1 + 0 + fib(1) + fib(0) + fib(1) 1+0 +1 +1+0 +1 +0 +1 =5 We see that fib(2) is computed 3 times. if (n==0   n==1) return n. 2 times in the above calculations. x=fib(n1) + fib(n2). We save the values of fib(2) or fib(3) and reuse them whenever needed. return (x). { clrscr (). and fib(3). fib(5)). of Information Technology . int x.
printf(“Enter the value of N and R :”).3f”. n. 2 Program to calculate the least common multiple of a given number: #include<stdio. scanf(“%d %d”. for (i = 0.h> float ncr (int n. prime. void main() { int n. } float ncr (int n. else return(n * 1. } int alone (int a[].h> int alone(int a[]. i < n. result = ncr(n. 2)). &n).7. of Information Technology . &r). r1)). result.00 2. int r). k < n. } Output: Enter the value of N and R: 5 The NCR value is: 10. scanf(“%d”. printf (“The least common multiple is %ld”. Program using recursion to calculate the NCR of a given number: #include<stdio.6. &a[i]). int prime). k++) if (a[k] != 1) return 0. &n.2. r). lcm(a. int r) { if(r == 0) return 1. printf (“Enter the numbers : “). for (k = 0. void main() { int a[20]. i++) scanf(“%d”.0 / r * ncr (n1. long int lcm(int a[]. int n). int n. result). int n). i. { int k. status. printf(“The NCR value is %. return 1. n. r. } Lecture Notes 20 Dept. printf (“Enter the limit: “).
of Information Technology . int n.8. Program to calculate the greatest common divisor: #include<stdio. status = 0. n. &n). } Output: Enter the limit: 6 Enter the numbers: 6 5 4 3 2 1 The least common multiple is 60 2. if (allone(a. status. } if (status == 1) return (prime * lcm(a. for (i = 0. int n. i ++) scanf (“%d”. i++) if (prime > a[i]) return 1. void main() { int a[20]. i++) if ((a[i] % prime) == 0) { status = 1. i. int prime) { int i. return 0. long int gcd (int a[]. i < n. n)) return 1. int check_all (int a[]. int prime) { int i.long int lcm (int a[]. scanf (“%d”. prime)). gcd (a. n. &a[i]). for (i = 0. int prime). printf (“Enter the numbers: “). n. a[i] = a[i] / prime. i < n. for (i = 0. } int check_limit (int a[]. int prime). prime = (prime == 2) ? prime+1 : prime+2)). 2)). int n. i < n.h> int check_limit (int a[]. int prime). int n. stat. prime. printf (“Enter the limit: “). } Lecture Notes 21 Dept. int n. printf (“The greatest common divisor is %ld”. n. else return (lcm (a.
for (i = 0. n. int prime) { int i. Don't use arrays/strings. The function will write 2^n1 integers (where ^ is the exponentiation operation). if (check_all (a. What is the importance of the stopping case in recursive functions? 2. if (check_limit(a. i++) if ((a[i] % prime) != 0) return 0. n. Note that the output for n always consists of the output for n1. else return (gcd (a. i < n. n. Lecture Notes 22 Dept. Here are the patterns of output for various values of n: n=1: n=2: n=3: n=4: Output Output Output Output is: is: is: is: 1 121 1213121 121312141213121 And so on. int prime) { int i. Write a function using Recursion to enter and display a string in reverse and state whether the string contains any spaces. followed by n itself. } Output: Enter the limit: 5 Enter the numbers: 99 55 22 The greatest common divisor is 11 77 121 Exercises 1. Write a function using Recursion to print numbers from n to 0. i++) a[i] = a[i] / prime. 6. 3. prime)). for (i = 0. int n. Which method is preferable in general? a) Recursive method b) Nonrecursive method 5. prime = (prime == 2) ? prime+1 : prime+2)). int n. prime)) return 1. } long int gcd (int a[]. Write a function with one positive integer parameter called n. followed by a second copy of the output for n1. return 1. prime)) return (prime * gcd (a. Write a recursive function for the mathematical function: f(n) = 1 if n = 1 f(n) = 2 * f(n1) if n >= 2 4.int check_all (int a[]. of Information Technology . n. i < n.
”). what is the maximum number of statements that may be recursive calls? A. Write a function using Recursion to enter characters one by one until a space is encountered. super_write_vertical(1023) [ ] Lecture Notes 23 Dept. 1 B. The function should return the depth at which the space was encountered. number < 10 C. super_write_vertical(1023) B. number). Consider the following function: void super_write_vertical (int number) { if (number < 0) { printf(“ . else { super_write_vertical(number/10). } else if (number < 10) printf(“%d\n”. Write a function using Recursion to check if a number n is prime. There is no fixed maximum [ ] 2. 1 B. 2 C. 2 C. Consider the following function: void super_write_vertical(int number) { if (number < 0) { printf(“ . } else if (number < 10) printf(“%d\n”. printf(“%d\n”. (You have to check whether n is divisible by any number below n) 8. else { super_write_vertical(number/10). } } What values of number are directly handled by the stopping case? A. printf(“%d\n”. In a single function declaration. } } Which call will result in the most recursive calls? A. What is the maximum depth of recursive calls a function may make? A.”).7. Multiple Choice Questions 1. super_write_vertical(abs(number)). number % 10). number). super_write_vertical(100) D. There is no fixed maximum [ ] 3. super_write_vertical(0) C. number % 10). number >= 0 && number < 10 D. n (where n is the argument) D. n (where n is the argument) D. number > 10 [ ] 4. of Information Technology . super_write_vertical (abs(number)). number < 0 B.
Communitivity. which information is not saved in the activation record? A. 3 B. of Information Technology . In a real computer. Parameters are all treated as reference arguments B. } How many asterisks are printed by the function call quiz(5)? A. Consider this function declaration: [ ] void quiz (int i) { if (i > 1) { quiz(i / 2). The program keeps running until you press CtrlC C. Mathematical induction. quiz(i / 2). C. When the compiler compiles your program. B. The operating system detects the infinite recursion because of the "repeated state" B. } printf(“ * ”). What technique is often used to prove the correctness of a recursive function? A. When a function call is executed. Matrix Multiplication. Parameters are all treated as value arguments C. Current depth of recursion. D.5. 4 C. D. 8 6. 7 D. The runtime stack overflows. how is a recursive call treated differently than a nonrecursive function call? A. halting the program [ ] 7. B. None of the above [ ] 8. The results are nondeterministic D. Local variables [ ] 9. [ ] Lecture Notes 24 Dept. what will happen if you make a recursive call without making the problem smaller? A. Formal parameters. C. Diagonalization. Location where the function should return when done. There is no duplication of local variables D.
some applications require enhancements to the linked list design. Once the array is set up. The linked list code will depend on the following functions: malloc() is a system function which allocates a block of memory in the "heap" and returns a pointer to the new block. of Information Technology . These enhancements fall into three broad categories and yield variations on linked lists that can be used in any combination: circular linked lists.h. int *ip. We can also use the sizeof() function to specify the number of bytes. Here is a quick review of the terminology and rules of pointers. It is defined by: void *malloc (number_of_bytes) Since a void * is returned the C standard states that this pointer can be converted to any type. but they happen to be strong where arrays are weak. Generally array's allocates the memory for all its elements in one block whereas linked lists use an entirely different strategy. queues etc. double linked lists and lists with header nodes. the list data structure is presented. Attempts to get 100 bytes and assigns the starting address to cp. Array is the most common data structure used to store collections of elements. malloc() returns NULL if it cannot fulfill the request. However. • Inserting new elements at the front is potentially expensive because existing elements need to be shifted over to make room. The disadvantages of arrays are: • The size of the array is fixed. Most often this size is specified at compile time. Linked lists and arrays are similar since they both store collections of data. char *cp. For example. ip = (int *) malloc (100*sizeof(int)). • Deleting an element from an array is not possible. The basic linked list can be used without modification in many programs. For example. Lecture Notes 25 Dept. The prototype of malloc() and other heap functions are in stdlib.Chapter 3 LINKED LISTS In this chapter. This makes the programmers to allocate arrays. which seems "large enough" than required. Linked lists have their own strengths and weaknesses. cp = (char *) malloc (100). Linked lists allocate memory for each element separately and only when necessary.). This structure can be used as the basis for the implementation of other data structures (stacks. Arrays are convenient to declare and provide the easy syntax to access any element by its index number. access to any element is convenient and fast.
free() is the opposite of malloc(), which deallocates memory. The argument to free()
is a pointer to a block of memory in the heap — a pointer which was obtained by a
malloc() function. The syntax is:
free (ptr);
The advantage of free() is simply memory management when we no longer need a
block.
3.1.
Linked List Concepts:
A linked list is a nonsequential collection of data items. It is a dynamic data structure.
For every data item in a linked list, there is an associated pointer that would give the
memory location of the next data item in the linked list.
The data items in the linked list are not in consecutive memory locations. They may be
anywhere, but the accessing of these data items is easier as each data item contains
the address of the next data item.
Advantages of linked lists:
Linked lists have many advantages. Some of the very important advantages are:
1.
2.
3.
4.
Linked lists are dynamic data structures. i.e., they can grow or shrink during
the execution of a program.
Linked lists have efficient memory utilization. Here, memory is not preallocated. Memory is allocated whenever it is required and it is deallocated
(removed) when it is no longer needed.
Insertion and Deletions are easier and efficient. Linked lists provide flexibility
in inserting a data item at a specified position and deletion of the data item
from the given position.
Many complex applications can be easily carried out with linked lists.
Disadvantages of linked lists:
1.
2.
3.2.
It consumes more space because every node requires a additional pointer to
store address of the next node.
Searching a particular element in list is difficult and also time consuming.
Types of Linked Lists:
Basically we can put linked lists into the following four items:
1.
Single Linked List.
2.
Double Linked List.
3.
Circular Linked List.
4.
Circular Double Linked List.
A single linked list is one in which all nodes are linked together in some sequential
manner. Hence, it is also called as linear linked list.
Lecture Notes
26
Dept. of Information Technology
A double linked list is one in which all nodes are linked together by multiple links which
helps in accessing both the successor node (next node) and predecessor node
(previous node) from any arbitrary node within the list. Therefore each node in a
double linked list has two link fields (pointers) to point to the left node (previous) and
the right node (next). This helps to traverse in forward direction and backward
direction.
A circular linked list is one, which has no beginning and no end. A single linked list can
be made a circular linked list by simply storing address of the very first node in the link
field of the last node.
A circular double linked list is one, which has both the successor pointer and
predecessor pointer in the circular manner.
Comparison between array and linked list:
ARRAY
LINKED LIST
Size of an array is fixed
Size of a list is not fixed
Memory is allocated from stack
Memory is allocated from heap
It is necessary to specify the number of
elements during declaration (i.e., during
compile time).
It is not necessary to specify the
number of elements during declaration
(i.e., memory is allocated during run
time).
It occupies more memory.
It occupies less memory than a linked
list for the same number of elements.
Inserting new elements at the front is
potentially expensive because existing
elements need to be shifted over to
make room.
Deleting an element from an array is
not possible.
Inserting a new element at any position
can be carried out easily.
Deleting an element is possible.
Trade offs between linked lists and arrays:
FEATURE
ARRAYS
LINKED LISTS
Sequential access
efficient
efficient
Random access
efficient
inefficient
Resigning
inefficient
efficient
Element rearranging
inefficient
efficient
Overhead per elements
none
1 or 2 links
Lecture Notes
27
Dept. of Information Technology
Applications of linked list:
1.
Linked lists are used to represent and manipulate polynomial. Polynomials are
expression containing terms with non zero coefficient and exponents. For
example:
P(x) = a0 Xn + a1 Xn1 + …… + an1 X + an
2.
Represent very large numbers and operations of the large number such as
addition, multiplication and division.
3.
Linked lists are to implement stack, queue, trees and graphs.
4.
Implement the symbol table in compiler construction
3.3.
Single Linked List:
A linked list allocates space for each element separately in its own block of memory
called a "node". The list gets an overall structure by using pointers to connect all its
nodes together like the links in a chain. Each node contains two fields; a "data" field to
store whatever element, and a "next" field which is a pointer used to link to the next
node. Each node is allocated in the heap using malloc(), so the node memory
continues to exist until it is explicitly deallocated using free(). The front of the list is a
pointer to the “start” node.
A single linked list is shown in figure 3.2.1.
STACK
HEAP
100
start
The start
pointer holds
the address
of the first
node of the
list.
10
200
100
Each node stores
the data.
20
300
200
30
300
Stores the next
node address.
400
40
X
400
The next field of the
last node is NULL.
Figure 3.2.1. Single Linked List
The beginning of the linked list is stored in a "start" pointer which points to the first
node. The first node contains a pointer to the second node. The second node contains a
pointer to the third node, ... and so on. The last node in the list has its next field set to
NULL to mark the end of the list. Code can access any node in the list by starting at the
start and following the next pointers.
The start pointer is an ordinary local pointer variable, so it is drawn separately on the
left top to show that it is in the stack. The list nodes are drawn on the right to show
that they are allocated in the heap.
Lecture Notes
28
Dept. of Information Technology
Implementation of Single Linked List:
Before writing the code to build the above list, we need to create a start node, used to
create and access other nodes in the linked list. The following structure definition will
do (see figure 3.2.2):
•
Creating a structure with one data item and a next pointer, which will be
pointing to next node of the list. This is called as selfreferential structure.
•
Initialise the start pointer to be NULL.
struct slinklist
{
int data;
struct slinklist* next;
};
node:
data
typedef struct slinklist node;
next
start
Empty list:
node *start = NULL;
NULL
Figure 3.2.2. Structure definition, single link node and empty list
The basic operations in a single linked list are:
•
Creation.
•
Insertion.
•
Deletion.
•
Traversing.
Creating a node for Single Linked List:
Creating a singly linked list starts with creating a node. Sufficient memory has to be
allocated for creating a node. The information is stored in the memory, allocated by
using the malloc() function. The function getnode(), is used for creating a node, after
allocating memory for the structure of type node, the information for the item (i.e.,
data) has to be read from the user, set next field to NULL and finally returns the
address of the node. Figure 3.2.3 illustrates the creation of a node for single linked list.
node* getnode()
{
node* newnode;
newnode = (node *) malloc(sizeof(node));
printf("\n Enter data: ");
scanf("%d", &newnode > data);
newnode > next = NULL;
return newnode;
}
newnode
10
X
100
Figure 3.2.3. new node with a value of 10
Lecture Notes
29
Dept. of Information Technology
} e ls e { te m p = st a rt. Figure 3. assign new node as start. no d e *t e m p .4 shows 4 items in a single linked list stored at different locations in memory.> ne xt = ne w no d e. start node) in the list by assigning the address of the first node.2. • The start pointer is made to point the new node by assigning the address of the new node. • If the list is not empty. start 100 10 100 200 20 300 200 30 400 300 40 X 400 Figure 3. w hile(t e m p .2. newnode = getnode(). if(st a rt = = N U L L) { sta rt = ne w no d e. no d e * ne w no d e.4.Creating a Singly Linked List with ‘n’ number of nodes: The following steps are to be followed to create ‘n’ number of nodes: • Get the new node using getnode(). follow the steps given below: • • The next field of the new node is made to point the first node (i. i+ + ) { ne w no d e = g et no d e(). Repeat the above steps ‘n’ times. • If the list is empty. fo r( i = 0.> ne xt ! = N U L L) te m p = t e m p .e. of Information Technology .> ne xt. Single Linked List with 4 nodes The function createlist(). is used to create ‘n’ number of nodes: vo id c r e at e list( int n) { int i. te m p . start = newnode. } } } Lecture Notes 30 Dept. i < n .
of Information Technology . • If the list is not empty. Inserting a node at the beginning The function insert_at_beg(). newnode = getnode(). start = newnode. if(start == NULL) { start = newnode. • Inserting a node at the end. start 500 10 100 5 200 20 300 200 30 400 300 40 X 400 100 500 Figure 3. The next field of the new node is assigned to NULL. • If the list is empty then start = newnode.5 shows inserting a node into the single linked list at the beginning.2. } else { newnode > next = start. The data field of the new node is then stored with the information read from the user.Insertion of a Node: One of the most primitive operations that can be done in a singly linked list is the insertion of a node. Inserting a node at the beginning: The following steps are to be followed to insert a new node at the beginning of the list: • Get the new node using getnode(). } } Lecture Notes 31 Dept. • Inserting a node at intermediate position.2. is used for inserting a node at the beginning void insert_at_beg() { node *newnode. follow the steps given below: newnode > next = start. start = newnode. Figure 3. The new node will contain empty data field and empty next field.5. The new node can then be inserted at three different places namely: • Inserting a node at the beginning. Memory is to be allocated for the new node (in a similar way that is done while creating a list) before reading the data. newnode = getnode().
while(temp > next != NULL) temp = temp > next. newnode = getnode(). if(start == NULL) { start = newnode. } else { temp = start.2. while(temp > next != NULL) temp = temp > next.6.6 shows inserting a node into the single linked list at the end. Inserting a node at the end. temp > next = newnode. is used for inserting a node at the end. • If the list is empty then start = newnode. • If the list is not empty follow the steps given below: temp = start.Inserting a node at the end: The following steps are followed to insert a new node at the end of the list: • Get the new node using getnode() newnode = getnode(). } } Inserting a node at intermediate position: The following steps are followed. Lecture Notes 32 Dept. of Information Technology . to insert a new node in an intermediate position in the list: • Get the new node using getnode(). Figure 3. void insert_at_end() { node *newnode. start 100 10 100 200 20 300 200 30 40 400 300 500 400 50 X 500 Figure 3. temp > next = newnode. *temp. The function insert_at_end(). newnode = getnode().2.
This is done by countnode() function. If not. nodectr. while(ctr < pos) { prev = temp. • Store the starting address (which is in start pointer) in temp and prev pointers. void insert_at_mid() { node *newnode. scanf("%d".2. &pos). Figure 3. int pos. } else { printf("position %d is not a middle position". temp = temp > next. nodectr = countnode(start). of Information Technology . newnode = getnode(). Inserting a node at an intermediate position. *prev. *temp. ctr++. printf("\n Enter the position: "). is used for inserting a node in the intermediate position. pos). } prev > next = newnode. • After reaching the specified position.2. } } Lecture Notes 33 Dept. ctr = 1. newnode > next = temp. follow the steps given below: prev > next = newnode.7. The function insert_at_mid(). newnode > next = temp. if(pos > 1 && pos < nodectr) { temp = prev = start.• Ensure that the specified position is in between first node and last node. Then traverse the temp pointer upto the specified position followed by prev pointer.7 shows inserting a node into the single linked list at a specified intermediate position other than beginning and end. • Let the intermediate position be 3. start prev temp 100 10 100 200 20 500 200 30 400 300 50 500 40 X 400 300 new node Figure 3. specified position is invalid.
8 shows deleting a node at the beginning of a single linked list. • Deleting a node at the beginning.2. Memory is to be released for the node to be deleted. Figure 3.. Deleting a node at the beginning. printf("\n Node deleted "). } } Lecture Notes 34 Dept.8. if(start == NULL) { printf("\n No nodes are exist. follow the steps given below: temp = start. start = start > next. is used for deleting the first node in the list. to delete a node at the beginning of the list: • If list is empty then display ‘Empty List’ message. • Deleting a node at intermediate position. start = temp > next. The function delete_at_beg(). } else { temp = start. Deleting a node at the beginning: The following steps are followed. free(temp). • If the list is not empty. start 200 10 temp 100 200 20 300 200 30 400 300 40 X 400 Figure 3. void delete_at_beg() { node *temp."). of Information Technology . free(temp). • Deleting a node at the end.Deletion of a node: Another primitive operation that can be done in a singly linked list is the deletion of a node.2. return . A node can be deleted from the list from three different places namely.
9 shows deleting a node at the end of a single linked list. of Information Technology ."). The function delete_at_last(). temp = temp > next. Figure 3. } prev > next = NULL. } prev > next = NULL.2. Deleting a node at the end. free(temp). if(start == NULL) { printf("\n Empty List. while(temp > next != NULL) { prev = temp. • If the list is not empty. } else { temp = start. temp = temp > next. follow the steps given below: temp = prev = start. prev = start. is used for deleting the last node in the list. *prev.Deleting a node at the end: The following steps are followed to delete a node at the end of the list: • If list is empty then display ‘Empty List’ message. return . } } Lecture Notes 35 Dept. printf("\n Node deleted ").9.2.. while(temp > next != NULL) { prev = temp. free(temp). void delete_at_last() { node *temp. start 100 10 100 200 20 300 200 X 30 300 40 X 400 Figure 3.
2. free(temp). ctr = 1. while(ctr < pos) { prev = temp. if(start == NULL) { printf("\n Empty List. node *temp."). return . &pos). printf("\n node deleted.. start 100 10 100 300 20 300 200 30 400 300 40 X 400 Figure 3. is used for deleting the intermediate node in the list.. *prev."). to delete a node from an intermediate position in the list (List must contain more than two node).2.Deleting a node at Intermediate position: The following steps are followed. scanf("%d". if(pos > nodectr) { printf("\nThis node doesnot exist"). Deleting a node at an intermediate position. pos.10 shows deleting a node at a specified intermediate position other than beginning and end from a single linked list. void delete_at_mid() { int ctr = 1. nodectr.10. The function delete_at_mid(). } Lecture Notes 36 Dept. } prev > next = temp > next. } else { printf("\n Enter position of node to delete: "). • If list is empty then display ‘Empty List’ message • If the list is not empty. of Information Technology . temp = temp > next. if(pos > 1 && pos < nodectr) { temp = prev = start. nodectr = countnode(start). ctr++. } Figure 3. follow the steps given below.
of Information Technology . • Display the information from the data field of each node. until the end of the list is reached. } else { printf("\n Invalid position. node by node from the first node. } } printf("X"). if(start == NULL ) printf("\n Empty List"). printf("\n Node deleted. The function traverse() is used for traversing and displaying the information stored in the list from left to right. } prev > next = temp > next. printf("\n The contents of List (Left to Right): \n"). else { while (temp != NULL) { printf("%d >"..").. getch(). } Alternatively there is another way to traverse and display the information. ctr ++. temp = temp > next.if(pos > 1 && pos < nodectr) { temp = prev = start."). Lecture Notes 37 Dept. void traverse() { node *temp. you have to traverse (move) a linked list. temp = temp > next. is used for traversing and displaying the information stored in the list from right to left. temp > data). while(ctr < pos) { prev = temp. temp = start. The function rev_traverse(). free(temp). That is in reverse order. Traversing a list involves the following steps: • Assign the address of start pointer to a temp pointer. } } } Traversal and displaying a list (Left to Right): To display the information.
printf("\n 7. }. clrscr(). printf("\n 6.Traverse the list (Right to Left)").Insert a node at middle"). } } Counting the Number of Nodes: The following code will count the number of nodes exist in the list using recursion.h> struct slinklist { int data. e ls e r et ur n(1 + co unt no d e(st .Delete a node from Middle"). struct slinklist *next. printf("\n 1.3.> d at a). printf("\n"). Source Code for the Implementation of Single Linked List: # include <stdio. int co unt no d e( no d e *st) { if(st = = N U L L) r et ur n 0. printf("\n 5.> ne xt). Lecture Notes 38 Dept. } 3.> " . typedef struct slinklist node.h> # include <conio.> ne xt)).1. int menu() { int ch. printf("\n"). printf("\n 8. printf("\n 2.vo id r e v_t r a v e rs e( no d e *st) { if(st = = N U L L) { r et ur n. node *start = NULL. printf("\n 9.Delete a node from Last"). printf("\n 4. printf("\n"). st . printf("\n 3.Create a list ").h> # include <stdlib. p r intf(" % d .Traverse the list (Left to Right)").Insert a node at end"). of Information Technology .Insert a node at beginning "). } e ls e { r e v_t r a v e rs e(st .Delete a node from beginning").
printf("\n 11.printf("\n"). Count nodes "). node *temp. &newnode > data). i++) { newnode = getnode(). for(i = 0. } node* getnode() { node * newnode. } else { temp = start. printf("\n\n Enter your choice: "). scanf("%d". } return (count). return. newnode > next = NULL. Exit ").&ch). } else { Lecture Notes 39 Dept. return ch. } void createlist(int n) { int i. printf("\n 10. temp = start. if(start == NULL) { start = newnode. of Information Technology . return newnode. node *newnode. while(temp > next != NULL) temp = temp > next. } int countnode(node *ptr) { int count=0. i < n. while(ptr != NULL) { count++. printf("\n The contents of List (Left to Right): \n"). ptr = ptr > next. if(start == NULL) { printf("\n Empty List"). scanf("%d". temp > next = newnode. newnode = (node *) malloc(sizeof(node)). } } } void traverse() { node *temp. printf("\n Enter data: ").
start > data). of Information Technology . } } void insert_at_mid() { node *newnode. } else { rev_traverse(start > next). while(temp > next != NULL) temp = temp > next. scanf("%d". void rev_traverse(node *start) { if(start == NULL) { return. nodectr = countnode(start). } } void insert_at_end() { node *newnode. *prev. newnode = getnode(). *temp. printf("%d >". nodectr. if(start == NULL) { start = newnode. ctr = 1. } } } printf(" X ").while(temp != NULL) { printf("%d>". int pos. } else { newnode > next = start. temp > data). } } void insert_at_beg() { node *newnode. if(start == NULL) { start = newnode. newnode = getnode(). newnode = getnode(). temp = temp > next. printf("\n Enter the position: "). } else { temp = start. temp > next = newnode. start = newnode. &pos). *temp. Lecture Notes 40 Dept.
temp = temp > next. free(temp). pos). } } void delete_at_last() { node *temp. } else printf("position %d is not a middle position". if(start == NULL) { printf("\n Empty List. temp = temp > next. start = temp > next."). while(ctr < pos) { prev = temp..} if(pos > 1 && pos < nodectr) { temp = prev = start. } } void delete_at_mid() { int ctr = 1. of Information Technology . *prev. if(start == NULL) { printf("\n No nodes are exist. node *temp. } prev > next = NULL. } prev > next = newnode. printf("\n Node deleted "). newnode > next = temp.. prev = start. if(start == NULL) { printf("\n Empty List. printf("\n Node deleted "). ctr++.")."). *prev. } else { temp = start. return . return . Lecture Notes 41 Dept. void delete_at_beg() { node *temp.. pos. } else { temp = start. while(temp > next != NULL) { prev = temp. free(temp). nodectr.
"). switch(ch) { case 1: if(start == NULL) { printf("\n Number of nodes you want to create: "). &pos). } if(pos > 1 && pos < nodectr) { temp = prev = start. temp = temp > next. if(pos > nodectr) { printf("\nThis node doesnot exist"). case 2: insert_at_beg(). free(temp)."). getch(). break. Lecture Notes 42 Dept.").. createlist(n). scanf("%d". while(1) { ch = menu(). break. printf("\n List created.. &n). of Information Technology ."). } void main(void) { int ch.} else { } } return . ctr ++. case 3: insert_at_end().. } prev > next = temp > next. break. clrscr().. printf("\n Enter position of node to delete: "). } else { printf("\n Invalid position. scanf("%d". while(ctr < pos) { prev = temp. break. printf("\n Node deleted. case 4: insert_at_mid(). n. } else printf("\n List is already created. nodectr = countnode(start).
break. delete_at_last().4. Similarly. rev_traverse(start). countnode(start)). printf(" X "). node n can never be the first node in the list. case 11 : exit(0). Using a header node: A header node is a special dummy node found at the front of the list. there is no need for the special case code given above for the remove operation. For example. traverse(). case 9: } 3. case 10: printf("\n No of nodes : %d ". break. delete_at_mid(). 20 and 30 would be represented using a linked list without and with a header node: sta rt 100 10 200 100 20 300 200 X 30 300 Si n g l e L i n k e d L i st w it h o ut a h e a d er n o d e sta rt 400 100 400 10 200 100 20 300 200 30 X 300 Si n g l e L i n k e d L i st w it h h e a d er n o d e Note that if your linked lists do include a header node. Lecture Notes 43 Dept. break. break. having a header node can simplify the code that adds a node before a given node n. } printf("\n The contents of List (Right to Left): \n"). The use of header node is an alternative to remove the first node in a list. of Information Technology . break. the picture below shows how the list with data 10. so there is no need to check for that case. break. } getch().case 5: case 6: case 7: case 8: delete_at_beg().
6. that information can be obtained very quickly. Right link. start a 100 a 200 100 b 300 200 c 300 Conceptual structure X b c d Implementation Figure 3. The basic operations in a double linked list are: • • • • Creation. 3. Data. if the current length is maintained in a header node. you can preallocate the nodes in a single array. In fact. you must remember not to include the header node in the count of "real" nodes in the list. For example searching for a name in a telephone directory would need forward and backward scanning thru a region of the whole list. Each node contains three fields: • • • Left link. Figure 3. Array based linked lists: Another alternative is to allocate the nodes in blocks.1 shows an example of null terminated single linked list where all the nodes are allocated contiguously in an array. In a standard linked list. For example.1. you must remember to initialize an empty list to contain one (dummy) node.5. The left link points to the predecessor node and the right link points to the successor node. of Information Technology . the list function to count the number of nodes has to traverse the entire list every time. Many applications require searching forward and backward thru nodes of a list.Note that if you do decide to use a header node. if you know the maximum size of a list a head of time.5. Lecture Notes 44 Dept. Traversing. It provides bidirectional traversing. This helps in accessing both successor node and predecessor node from the given node position. Insertion. imagine an application in which the number of items in a list is often calculated.5. An array based linked list 3. It is also useful when information other than that found in each node of the list is needed. However. Double Linked List: A double linked list is a twoway list in which all nodes will have two links. The data field stores the required data. Deletion. The result is a hybrid structure – an array based linked list.
A double linked list is shown in figure 3. newnode > right = NULL. The function getnode(). node* getnode() { node* new node. NULL Figure 3. after allocating memory for the structure of type node. of Information Technology .1. The information is stored in the memory. int data. X 10 200 100 100 20 300 200 200 Stores the data. data) has to be read from the user and set left field to NULL and right field also set to NULL (see figure 3.1. the information for the item (i. X 30 300 Stores the next node address. node *start = NULL. newnode = (node *) malloc(sizeof(node)). } newnode X 10 X 100 Figure 3.1. newnode > left = NULL. scanf("%d".2. data right start Empty list: typedef struct dlinklist node. allocated by using the malloc() function. STACK 100 start The start pointer holds the address of the first node of the list. The right field of the last node is NULL.. return new node. HEAP Stores the previous node address. struct dlinklist *right. The following code gives the structure definition: struct dlinklist { struct dlinklist *left.4. Sufficient memory has to be allocated for creating a node. printf("\n Enter data: "). double link node and empty list Creating a node for Double Linked List: Creating a double linked list starts with creating a node. new node with a value of 10 Lecture Notes 45 Dept. is used for creating a node.3. Figure 3. node: left }. Structure definition.4.3. The first node’s left link and last node’s right link is set to NULL. &newnode > data). Double Linked List The beginning of the double linked list is stored in a "start" pointer which points to the first node.2).e.2.
ne w no d e . no d e * ne w no d e.> left = t e m p . Double Linked List with 3 nodes Lecture Notes 46 Dept. i < n. • The previous nodes right field must be assigned with address of the new node. newnode =getnode(). } e ls e { te m p = st a rt.Creating a Double Linked List with ‘n’ number of nodes: The following steps are to be followed to create ‘n’ number of nodes: • Get the new node using getnode(). start 100 X 100 10 200 100 20 300 200 200 30 X 300 Figure 3. • If the list is not empty.> r ig ht = ne w no d e. if(st a rt = = N U L L) { sta rt = ne w no d e. of Information Technology . follow the steps given below: • • The left field of the new node is made to point the previous node. The function createlist().> r ig ht.> r ig ht) te m p = t e m p . w hile(t e m p . } } } Figure 3.3.4. • If the list is empty then start = newnode. no d e *t e m p . i+ + ) { ne w no d e = g et no d e(). fo r( i = 0.4. Repeat the above steps ‘n’ times. is used to create ‘n’ number of nodes: vo id c r e at e list( int n) { int i.3 shows 3 items in a double linked list stored at different locations. te m p .
5 shows inserting a node into the double linked list at the end. Figure 3. Inserting a node at the beginning Inserting a node at the end: The following steps are followed to insert a new node at the end of the list: • Get the new node using getnode() newnode=getnode(). Figure 3. follow the steps given below: newnode > right = start. The function dbl_insert_beg(). Lecture Notes 47 Dept. while(temp > right != NULL) temp = temp > right. • If the list is not empty follow the steps given below: temp = start.4. • If the list is empty then start = newnode. temp > right = newnode. is used for inserting a node at the end.Inserting a node at the beginning: The following steps are to be followed to insert a new node at the beginning of the list: • Get the new node using getnode().4. is used for inserting a node at the beginning. start 400 400 10 200 100 X 40 100 20 300 200 200 30 X 300 100 400 Figure 3. • If the list is empty then start = newnode. The function dbl_insert_end().4. start = newnode. of Information Technology .4. newnode=getnode(). start > left = newnode.4 shows inserting a node into the double linked list at the beginning. newnode > left = temp. • If the list is not empty.
• Store the starting address (which is in start pointer) in temp and prev pointers. The function dbl_insert_mid(). This is done by countnode() function.4.5. Then traverse the temp pointer upto the specified position followed by prev pointer. is used for inserting a node in the intermediate position. newnode=getnode(). • Ensure that the specified position is in between first node and last node.6.4. of Information Technology . temp > right = newnode. Figure 3. specified position is invalid. to insert a new node in an intermediate position in the list: • Get the new node using getnode().4. • After reaching the specified position.6 shows inserting a node into the double linked list at a specified intermediate position other than beginning and end. Inserting a node at an intermediate position Lecture Notes 48 Dept. If not. follow the steps given below: newnode > left = temp. Inserting a node at the end Inserting a node at an intermediate position: The following steps are followed.start 100 X 10 200 100 100 20 300 200 200 30 400 40 X 300 300 400 Figure 3. newnode > right = temp > right. start 100 100 400 X 10 400 40 200 400 20 300 200 100 200 30 X 300 Figure 3. temp > right > left = newnode.
follow the steps given below: temp = start. Figure 3. is used for deleting the first node in the list. The function dbl_delete_beg(). Deleting a node at beginning Deleting a node at the end: The following steps are followed to delete a node at the end of the list: • If list is empty then display ‘Empty List’ message • If the list is not empty. start > left = NULL. Deleting a node at the end Lecture Notes 49 Dept.4. free(temp). start 200 X 10 200 100 X 20 200 300 200 30 X 300 Figure 3. start 100 X 100 10 200 100 20 X 200 200 30 X 300 Figure 3. The function dbl_delete_last(). to delete a node at the beginning of the list: • If list is empty then display ‘Empty List’ message.7.7 shows deleting a node at the end of a double linked list. free(temp).6 shows deleting a node at the beginning of a double linked list. follow the steps given below: temp = start.Deleting a node at the beginning: The following steps are followed. • If the list is not empty.4.6. of Information Technology . start = start > right.4. } temp > left > right = NULL. is used for deleting the last node in the list. Figure 3.4. while(temp > right != NULL) { temp = temp > right.
• If list is empty then display ‘Empty List’ message. is used for deleting the intermediate node in the list. • If the list is not empty. until the end of the list is reached. • Ensure that the specified position is in between first node and last node. Figure 3. start 100 X 100 10 300 100 20 300 200 100 30 X 300 Figure 3.. free(temp). • If the list is not empty. i = 1.4. while(i < pos) { temp = temp > right. • Then perform the following steps: if(pos > 1 && pos < nodectr) { temp = start. follow the steps given below: Lecture Notes 50 Dept. If not. node by node from the first node. of Information Technology ."). printf("\n node deleted.Deleting a node at Intermediate position: The following steps are followed. to delete a node from an intermediate position in the list (List must contain more than two nodes).8 Deleting a node at an intermediate position Traversal and displaying a list (Left to Right): To display the information. The following steps are followed. The function traverse_left_right() is used for traversing and displaying the information stored in the list from left to right. temp > left > right = temp > right. specified position is invalid.4. you have to traverse the list. i++. to traverse a list from left to right: • If list is empty then display ‘Empty List’ message. } temp > right > left = temp > left.8 shows deleting a node at a specified intermediate position other than beginning and end from a double linked list. follow the steps given below: • Get the position of the node to delete. } The function delete_at_mid().
while(temp != NULL) { print temp > data. typedef struct dlinklist node. you have to traverse the list. }. • If the list is not empty. node *start = NULL. until the end of the list is reached. The function traverse_right_left() is used for traversing and displaying the information stored in the list from right to left. A Complete Source Code for the Implementation of Double Linked List: #include <stdio.5.> r ig ht )). temp = temp > right. int co unt no d e( no d e *st a rt) { if(st a rt = = N U L L) r et ur n 0. The following steps are followed. } Traversal and displaying a list (Right to Left): To display the information from right to left.h> #include <conio. struct dlinklist *right. to traverse a list from right to left: • If list is empty then display ‘Empty List’ message.h> #include <stdlib. while(temp != NULL) { print temp > data. e ls e r et ur n(1 + co unt no d e(st a rt . Lecture Notes 51 Dept. node by node from the first node. of Information Technology . } 3.h> struct dlinklist { struct dlinklist *left. follow the steps given below: temp = start.temp = start. temp = temp > left. int data. while(temp > right != NULL) temp = temp > right. } Counting the Number of Nodes: The following code will count the number of nodes exist in the list (using recursion).
Traverse the list from Right to Left ").Create"). if(start == NULL) start = newnode. Traverse the list from Left to Right "). newnode = (node *) malloc(sizeof(node)). printf("\n"). } } } Lecture Notes 52 Dept. Delete a node from Middle"). &newnode > data). i < n. Insert a node at beginning "). printf("\n 7. for(i = 0.node* getnode() { node * newnode. Insert a node at middle"). printf("\n 3. return ch. printf("\n 8. newnode > right = NULL. printf("\n\n Enter your choice: "). Delete a node from Last"). temp > right = newnode. newnode > left = temp. printf("\n 6. scanf("%d". } void createlist(int n) { int i. printf("\n").Count the Number of nodes in the list"). else return 1 + countnode(start > right). node *temp.Exit "). printf("\n 2. } int countnode(node *start) { if(start == NULL) return 0. printf("\n 4. Delete a node from beginning"). printf("\n"). node *newnode. } int menu() { int ch. printf("\n"). while(temp > right) temp = temp > right. printf("\n Enter data: "). return newnode. printf("\n 5. printf("\n 9. printf("\n 1. else { temp = start. &ch). Insert a node at end"). printf("\n 10. scanf("%d". newnode > left = NULL. clrscr(). of Information Technology . printf("\n 11. i++) { newnode = getnode().
else { temp = start. } } } void traverse_right_to_left() { node *temp. start > left = newnode. temp = start. if(start == NULL ) printf("\n Empty List"). newnode = getnode(). temp = temp > right. } } void dll_insert_end() { node *newnode. else { while(temp != NULL) { printf("\t %d ".void traverse_left_to_right() { node *temp. } while(temp != NULL) { printf("\t%d". of Information Technology . newnode > left = temp. temp > right = newnode. temp > data). temp = temp > left. if(start == NULL) printf("\n Empty List"). *temp. } } void dll_insert_beg() { node *newnode. if(start == NULL) start = newnode. printf("\n The contents of List: "). printf("\n The contents of List: "). newnode = getnode(). while(temp > right != NULL) temp = temp > right. temp > data). temp = start. else { while(temp > right != NULL) temp = temp > right. } } Lecture Notes 53 Dept. if(start == NULL) start = newnode. else { newnode > right = start. start = newnode.
free(temp). } void dll_delete_beg() { node *temp. int pos."). ctr = 1.*temp. return . if(start == NULL) { printf("\n Empty list"). &pos). } else { temp = start. scanf("%d". start = start > right. } else { temp = start.nodectr >= 2) { printf("\n Position is out of range. getch().void dll_insert_mid() { node *newnode. nodectr = countnode(start).1) { temp = temp > right. newnode = getnode(). while(ctr < pos . nodectr. of Information Technology . pos).. } } void dll_delete_last() { node *temp. if(start == NULL) { printf("\n Empty list"). start > left = NULL. while(temp > right != NULL) Lecture Notes 54 Dept. } if(pos > 1 && pos < nodectr) { temp = start. return . printf("\n Enter the position: "). } newnode > left = temp. getch(). temp > right > left = newnode. ctr++. } else printf("position %d of list is not a middle position ". return. newnode > right = temp > right. if(pos . temp > right = newnode.
&n). clrscr(). n. printf("\n node deleted. scanf("%d". i++. if(start == NULL) { printf("\n Empty List").. void dll_delete_mid() { int i = 0. getch(). return. temp > left > right = NULL. createlist(n). switch( ch) { case 1 : printf("\n Enter Number of nodes to create: "). if(pos > nodectr) { printf("\nthis node does not exist"). while(i < pos) { temp = temp > right. while(1) { ch = menu().. nodectr. return.")."). } temp > right > left = temp > left. } else { printf("\n Enter the position of the node to delete: ").} } temp = temp > right. } } } void main(void) { int ch. free(temp). of Information Technology . getch(). temp > left > right = temp > right. } if(pos > 1 && pos < nodectr) { temp = start. pos. scanf("%d". } else { printf("\n It is not a middle position. nodectr = countnode(start). getch(). free(temp). i = 1. temp = NULL. Lecture Notes 55 Dept. node *temp. &pos).
6. case 11: exit(0). In circular linked list no null pointers are used."). : dll_delete_beg().6. } } getch(). hence all pointers contain valid address. : dll_insert_mid(). Circular linked lists are frequently used instead of ordinary linked list because many operations are much easier to implement. : dll_delete_last(). of Information Technology . break. : dll_delete_mid(). start 100 10 100 200 20 300 200 30 400 300 40 100 400 Figure 3.case 2 case 3 case 4 case 5 case 6 case 7 case 8 case 9 printf("\n List created. break. break.1. : dll_insert_end(). break. C ircular Single Linked List Lecture Notes 56 Dept.1. break. break. It is necessary to establish a special pointer called start pointer always pointing to the first node of the list. : traverse_right_to_left(). : traverse_left_to_right(). case 10 : printf("\n Number of nodes: %d".7.. countnode(start)). : dll_insert_beg(). break. A circular single linked list is shown in figure 3. break. break. Circular Single Linked List: It is just a single linked list in which the link field of the last node points back to the address of the first node. break. } 3. A circular linked list has no beginning and no end.
The function createlist(). temp > next = newnode. Creating a circular single Linked List with ‘n’ number of nodes: The following steps are to be followed to create ‘n’ number of nodes: • Get the new node using getnode(). start = newnode. Insertion. start = newnode. is used to create ‘n’ number of nodes: Inserting a node at the beginning: The following steps are to be followed to insert a new node at the beginning of the circular list: • Get the new node using getnode(). last > next = start. • If the list is empty. newnode = getnode(). newnode > next = start. start = newnode. Lecture Notes 57 Dept. while(temp > next != NULL) temp = temp > next. follow the steps given below: temp = start. assign new node as start. • If the list is empty. while(last > next != start) last = last > next. Traversing. follow the steps given below: last = start.The basic operations in a circular single linked list are: • • • • Creation. • Repeat the above steps ‘n’ times. • If the list is not empty. • newnode > next = start. assign new node as start. newnode = getnode(). newnode > next = start. Deletion. of Information Technology . • If the list is not empty.
• If the list is not empty follow the steps given below: temp = start. of Information Technology .6. is used for inserting a node at the beginning.2.6. assign new node as start. is used for inserting a node at the end. start 100 10 100 200 20 300 200 30 40 400 300 500 400 50 100 500 Figure 3.6.6. while(temp > next != start) temp = temp > next.3 shows inserting a node into the circular single linked list at the end. Inserting a node at the beginning Inserting a node at the end: The following steps are followed to insert a new node at the end of the list: • Get the new node using getnode(). Figure 3. Figure 3.2 shows inserting a node into the circular single linked list at the beginning. temp > next = newnode. start 500 10 200 100 5 20 300 200 30 40 400 300 500 400 100 500 Figure 3. • If the list is empty. The function cll_insert_end(). newnode = getnode(). newnode > next = start.The function cll_insert_beg().3 Inserting a node at the end. Lecture Notes 58 Dept. newnode > next = start. start = newnode.
of Information Technology . prev = start. while(temp > next != start) { prev = temp.4. The function cll_delete_beg(). to delete a node at the beginning of the list: • If the list is empty.Deleting a node at the beginning: The following steps are followed. start = start > next.4 shows deleting a node at the beginning of a circular single linked list.6. if the list is empty then start = NULL. follow the steps given below: temp = start. Deleting a node at the end: The following steps are followed to delete a node at the end of the list: • If the list is empty. if the list is empty then start = NULL. } prev > next = start. • After deleting the node. • If the list is not empty. is used for deleting the last node in the list. temp = temp > next. The function cll_delete_last(). • After deleting the node.6. display a message ‘Empty List’. follow the steps given below: last = temp = start. while(last > next != start) last = last > next. start 200 10 temp 200 100 20 300 200 30 40 400 300 200 400 Figure 3. Lecture Notes 59 Dept. is used for deleting the first node in the list. last > next = start. Deleting a node at beginning. display a message ‘Empty List’. • If the list is not empty. Figure 3.
follow the steps given below: temp = start.h> # include <conio.7. node *start = NULL. newnode > next = NULL.5. scanf("%d".6. int nodectr. newnode = (node *) malloc(sizeof(node)). struct cslinklist *next.h> # include <stdlib. } while(temp != start). temp > data). typedef struct cslinklist node.Figure 3. Deleting a node at the end. return newnode. do { printf("%d ". node* getnode() { node * newnode.h> struct cslinklist { int data. start 100 10 200 100 20 300 200 30 100 300 40 100 400 Figure 3. }. temp = temp > next.6. Source Code for Circular Single Linked List: # include <stdio. &newnode > data). to traverse a list from left to right: • If list is empty then display ‘Empty List’ message. • If the list is not empty. 3. of Information Technology . printf("\n Enter data: "). } Lecture Notes 60 Dept. Traversing a circular single linked list from left to right: The following steps are followed.1.5 shows deleting a node at the end of a circular single linked list.
node *temp. printf("\n 9. if(start == NULL ) printf("\n Empty List"). Insert a node at beginning "). printf("\n\n"). Delete a node from beginning"). scanf("%d". Delete a node from Middle"). temp > next = newnode. printf("\n\n"). temp > data). } } newnode >next = start. printf("\n 5. printf(" X ").int menu() { int ch. temp = temp > next. printf("\n 1. printf("\n 6. return ch. if(start == NULL) { start = newnode. nodectr = n. Display the list"). of Information Technology . printf("\n\n"). &ch). printf("\n Enter your choice: "). printf("\n 7. Exit"). printf("\n 3. while(temp > next != NULL) temp = temp > next. Delete a node from Last"). /* last node is pointing to starting node */ } void display() { node *temp. Insert a node at middle"). else { do { printf("\t %d ". i++) { newnode = getnode(). printf("\n\n"). clrscr(). } } Lecture Notes 61 Dept. for(i = 0. } else { temp = start. Insert a node at end"). node *newnode. printf("\n 2. Create a list "). printf("\n The contents of List (Left to Right): "). printf("\n 8. } void createlist(int n) { int i. printf("\n 4. temp = start. } while(temp != start). i < n .
.void cll_insert_beg() { node *newnode. while(temp > next != start) temp = temp > next. i = 1. if(start == NULL) { start = newnode."). while(i < pos) { prev = temp. nodectr++. pos . start = newnode. temp > next = newnode. } void cll_insert_end() { node *newnode. newnode = getnode(). printf("\n Enter the position: "). newnode > next = start. if(pos > 1 && pos < nodectr) { temp = start. of Information Technology . newnode = getnode(). if(start == NULL ) { start = newnode. } printf("\n Node inserted at end. } else { last = start. last > next = start. while(last > next != start) last = last > next. *last. } prev > next = newnode. nodectr++. scanf("%d". } printf("\n Node inserted at beginning. newnode > next = start. Lecture Notes 62 Dept. newnode > next = start."). } else { temp = start. prev = temp. newnode = getnode(). newnode > next = start. *temp. int i. *temp. i++. temp = temp > next. newnode > next = temp. &pos).. } void cll_insert_mid() { node *newnode. *prev.
} } Lecture Notes 63 Dept. return . free(temp). nodectr. temp = temp > next. start = start > next. if(start == NULL) { printf("\n No nodes exist.")... } } void cll_delete_last() { node *temp... pos). nodectr. } else { last = temp = start. } else { temp = start."). printf("\n Node inserted at middle."). of Information Technology . } else { } printf("position %d of list is not a middle position ". getch().*prev. } void cll_delete_beg() { node *temp. *last. printf("\n Node deleted. while(last > next != start) last = last > next.. getch(). printf("\n Node deleted. if(start == NULL) { printf("\n No nodes exist. } prev > next = start. prev = start. last > next = start."). if(nodectr == 0) start = NULL. return . while(temp > next != start) { prev = temp.").nodectr++. if(nodectr == 0) start = NULL. free(temp).
} } void main(void) { int result. scanf("%d". getch(). } Lecture Notes 64 Dept. } if(start == NULL) { printf("\n No nodes exist. nodectr. of Information Technology . } prev > next = temp > next. pos.").. prev = start. switch(ch) { case 1 : if(start == NULL) { printf("\n Enter Number of nodes to create: "). *prev. i = 0. i++.. &n). } else { printf("\n Which node to delete: "). getch(). return. } if(pos > 1 && pos < nodectr) { temp=start.1) { prev = temp. return . while(i < pos ."). free(temp). while(1) { ch = menu(). temp = temp > next . if(pos > nodectr) { printf("\nThis node does not exist").."). int ch. &pos). printf("\nList created. printf("\n Node Deleted. clrscr(). createlist(n). n. getch(). scanf("%d".void cll_delete_mid() { int i = 0.").. node *temp. } else { printf("\n It is not a middle position.
break.. Insertion. break. 100 start 300 100 10 200 100 20 300 200 200 30 100 300 Figure 3. The objective behind considering circular double linked list is to simplify the insertion and deletion operations performed on double linked list. break.8. Circular Double Linked List: A circular double linked list has both successor pointer and predecessor pointer in circular manner. break. : cll_insert_beg()."). : cll_delete_mid().1. A circular double linked list is shown in figure 3. } getch(). : display(). break. : cll_delete_last(). In circular double linked list the right link of the right most node points back to the start node and left link of the first node points to the last node. : exit(0). : cll_insert_end(). : cll_insert_mid(). break. of Information Technology . Deletion.else case 2 case 3 case 4 case 5 case 6 case 7 case 8 case 9 } printf("\n List is already Exist. Lecture Notes 65 Dept. } 3.1. break. break.8. C ircular Double Linked List The basic operations in a circular double linked list are: • • • • Creation.8. : cll_delete_beg(). Traversing.
The function cdll_createlist(). • If the list is empty. • If the list is empty. start > left = newnode. • If the list is not empty. • Repeat the above steps ‘n’ times. follow the steps given below: newnode > left = start > left. newnode > left = start. then do the following start = newnode.Creating a Circular Double Linked List with ‘n’ number of nodes: The following steps are to be followed to create ‘n’ number of nodes: • Get the new node using getnode(). start > left = newnode. newnode > left = start. is used for inserting a node at the beginning. start 400 400 100 300 40 10 200 100 20 300 200 200 30 400 300 100 400 Figure 3. newnode > right = start. follow the steps given below: newnode > left = start > left. • If the list is not empty. newnode > right = start.8. newnode >right = start.8. then start = newnode. start > left > right = newnode. newnode > right = start.2 shows inserting a node into the circular double linked list at the beginning. newnode=getnode(). newnode = getnode(). Inserting a node at the beginning Lecture Notes 66 Dept. is used to create ‘n’ number of nodes: Inserting a node at the beginning: The following steps are to be followed to insert a new node at the beginning of the list: • Get the new node using getnode().2. of Information Technology . The function cdll_insert_beg(). start > left>right = newnode. start = newnode. Figure 3.
temp > right > left = newnode. Inserting a node at the end Inserting a node at an intermediate position: The following steps are followed. This is done by countnode() function. newnode=getnode(). nodectr++. start > left > right = newnode. is used for inserting a node at the end. of Information Technology .8. Figure 3. • After reaching the specified position. newnode > right = start. temp > right = newnode. newnode > right = start. • If the list is empty.Inserting a node at the end: The following steps are followed to insert a new node at the end of the list: • Get the new node using getnode() newnode=getnode(). newnode > right = temp > right.8. then start = newnode. The function cdll_insert_end(). • Store the starting address (which is in start pointer) in temp. start > left = newnode. newnode > left = start.3 shows inserting a node into the circular linked list at the end. specified position is invalid. start 100 400 100 10 200 100 20 200 300 200 30 400 300 300 40 100 400 Figure 3. Lecture Notes 67 Dept. Then traverse the temp pointer upto the specified position. If not. • If the list is not empty follow the steps given below: newnode > left = start > left. follow the steps given below: newnode > left = temp. to insert a new node in an intermediate position in the list: • Get the new node using getnode(). • Ensure that the specified position is in between first node and last node.3.
The function cdll_delete_beg(). is used for deleting the first node in the list. to delete a node at the beginning of the list: • If list is empty then display ‘Empty List’ message.5. temp > left > right = start. Inserting a node at an intermediate position Deleting a node at the beginning: The following steps are followed.8. • If the list is not empty. start = start > right. Figure 3. follow the steps given below: temp = start. follow the steps given below: Lecture Notes 68 Dept.5 shows deleting a node at the beginning of a circular double linked list.The function cdll_insert_mid(). is used for inserting a node in the intermediate position.4 shows inserting a node into the circular double linked list at a specified intermediate position other than beginning and end. start > left = temp > left. start 200 300 10 100 200 300 20 300 200 200 30 200 300 Figure 3. start 100 100 40 200 400 300 10 400 400 100 20 300 30 100 200 200 300 Figure 3. of Information Technology .4.8. Figure 3. Deleting a node at beginning Deleting a node at the end: The following steps are followed to delete a node at the end of the list: • • If list is empty then display ‘Empty List’ message If the list is not empty.8.8.
"). start 100 200 100 10 200 100 20 100 200 200 30 100 300 Figure 3.6 shows deleting a node at the end of a circular double linked list. } temp > left > right = temp > right. } temp > right > left = temp > left. while(i < pos) { temp = temp > right . of Information Technology .8. • Then perform the following steps: if(pos > 1 && pos < nodectr) { temp = start. is used for deleting the last node in the list. temp > left > right = temp > right. printf("\n node deleted. temp > right > left = temp > left.. • Ensure that the specified position is in between first node and last node. If not. Figure 3. to delete a node from an intermediate position in the list (List must contain more than two node). i++. free(temp). • If list is empty then display ‘Empty List’ message. The function cdll_delete_last(). i = 1.6. follow the steps given below: • Get the position of the node to delete.8. } The function cdll_delete_mid(). nodectr. specified position is invalid. is used for deleting the intermediate node in the list. Deleting a node at the end Deleting a node at Intermediate position: The following steps are followed. Lecture Notes 69 Dept. while(temp > right != start) { temp = temp > right. • If the list is not empty.temp = start.
start 100 300 100 10 300 100 20 100 300 200 30 100 300 Figure 3.8. temp = temp > right.7.1.8. Print temp > data. while(temp != start) { print temp > data. of Information Technology . temp = temp > right.h> # include <conio. • If the list is not empty. print temp > data. • If the list is not empty. is used for traversing from left to right.h> Lecture Notes 70 Dept. Traversing a circular double linked list from right to left: The following steps are followed. do { temp = temp > left. follow the steps given below: temp = start.8. Source Code for Circular Double Linked List: # include <stdio. follow the steps given below: temp = start. 3. is used for traversing from right to left. } while(temp != start). The function cdll_display_right_left().Figure 3. } The function cdll_display_left _right(). to traverse a list from left to right: • If list is empty then display ‘Empty List’ message.h> # include <stdlib. Deleting a node at an intermediate position Traversing a circular double linked list from left to right: The following steps are followed.7 shows deleting a node at a specified intermediate position other than beginning and end from a circular double linked list. to traverse a list from right to left: • If list is empty then display ‘Empty List’ message.
for(i = 0. Display the list from Right to Left"). Delete a node from End"). node *newnode. } else { newnode > left = start > left. printf("\n 1. return ch. printf("\n 3. } void cdll_createlist(int n) { int i. typedef struct cdlinklist node. printf("\n 5. Delete a node from Middle"). clrscr(). printf("\n 10. of Information Technology . printf("\n\n Enter your choice: "). int data. printf("\n\n").Exit"). return newnode. i < n. Create "). printf("\n Enter data: "). if(start == NULL) { nodectr = n. Delete a node from Beginning"). printf("\n\n").struct cdlinklist { struct cdlinklist *left. newnode > left = NULL. scanf("%d". node *start = NULL. newnode >right = start. struct cdlinklist *right. } int menu() { int ch. scanf("%d". int nodectr. printf("\n 9. i++) { newnode = getnode(). printf("\n 4. &newnode > data). Insert a node at Beginning"). newnode > right = NULL. newnode > left = start. *temp. Insert a node at Middle"). }. newnode = (node *) malloc(sizeof(node)). printf("\n 6. printf("\n 7. if(start == NULL) { start = newnode. &ch). Display the list from Left to Right"). printf("\n 8. Lecture Notes 71 Dept. printf("\n\n"). printf("\n 2. Insert a node at End"). node* getnode() { node * newnode.
start > left = newnode. } while(temp != start). newnode = getnode(). if(start == NULL) printf("\n Empty List"). do { temp = temp > left. if(start == NULL) { start = newnode. if(start == NULL) printf("\n Empty List"). else { printf("\n The contents of List: "). temp = temp > right. while(temp != start) { printf(" %d "."). newnode > left = start. newnode > right = start. else { printf("\n The contents of List: "). start > left>right = newnode. nodectr++..} else } } } newnode > right = start. } } } void cdll_display_right_left() { node *temp. temp = start. temp = temp > right. start > left = newnode. } else { newnode > left = start > left. start > left > right = newnode. temp = start. } } void cdll_insert_beg() { node *newnode. temp > data). printf("\t%d". printf("\n List already exists. void cdll_display_left_right() { node *temp. of Information Technology . temp > data). printf(" %d ". newnode > right = start. Lecture Notes 72 Dept. temp > data).
nodectr++. newnode > right = start. of Information Technology .. temp > right > left = newnode. *prev. if(pos . if(start == NULL) { printf("\n No nodes exist. ctr++. } else printf("position %d of list is not a middle position". } newnode > left = temp. newnode > right = temp > right. Lecture Notes 73 Dept. ").} start = newnode."). } void cdll_insert_mid() { node *newnode. printf("\n Node Inserted at Middle.. newnode = getnode(). ctr = 1. newnode > left = start. } void cdll_insert_end() { node *newnode. if(start == NULL) { start = newnode. &pos). int pos. } printf("\n Node Inserted at End")."). } } void cdll_delete_beg() { node *temp. pos).. while(ctr < pos . start > left = newnode.nodectr >= 2) { printf("\n Position is out of range. } if(pos > 1 && pos <= nodectr) { temp = start. temp > right = newnode. } else { newnode > left = start > left. scanf("%d". return. *temp.1) { temp = temp > right. newnode = getnode(). printf("\n Enter the position: "). start > left > right = newnode. newnode > right = start.*temp. nodectr++.
temp > left > right = start. } } void cdll_delete_mid() { int ctr = 1. node *temp. of Information Technology . return . if(start == NULL) { printf("\n No nodes exist. temp > right > left = temp > left. getch(). if(nodectr == 0) { free(start). pos. void cdll_delete_last() { node *temp... getch(). return. free(temp). free(temp). } Lecture Notes 74 Dept."). start = start > right.getch(). } printf("\n Node deleted at Beginning. return. if( start == NULL) { printf("\n No nodes exist."). start > left = temp > left. start = NULL. start = NULL."). while(temp > right != start) temp = temp > right. } else { nodectr. } else { temp = start. } else { temp = start.. } else { } } nodectr. temp > left > right = temp > right. } printf("\n Node deleted from end "). if(nodectr == 0) { free(start).
free(temp). case 5 : cdll_delete_beg(). getch().n. } } } void main(void) { int ch. break. nodectr."). printf("\n node deleted. break. break. getch(). } else { printf("\n It is not a middle position. of Information Technology . Lecture Notes 75 Dept. while(1) { ch = menu(). break.").else { printf("\n Which node to delete: "). scanf("%d". case 6 : cdll_delete_last(). case 3 : cdll_insert_end()."). switch( ch) { case 1 : printf("\n Enter Number of nodes to create: "). scanf("%d". break. while(ctr < pos) { temp = temp > right . &n). } temp > right > left = temp > left. } if(pos > 1 && pos < nodectr) { temp = start. ctr++. temp > left > right = temp > right.. cdll_createlist(n). if(pos > nodectr) { printf("\nThis node does not exist").. break. printf("\n List created. return. case 4 : cdll_insert_mid(). case 2 : cdll_insert_beg(). clrscr(). &pos)..
some applications lead naturally to circular list representations. the more fields that have to be maintained. Polynomials: A polynomial is of the form: n i ∑ ci x i =0 Where. The major advantage of doubly linked lists is that they make some operations (like the removal of a given node. Lecture Notes 76 Dept. a computer network might best be modeled using a circular list. The major advantage of circular lists (over noncircular lists) is that they eliminate some extracase code for some operations (like deleting last node). break. break. case 9 : cdll_display_right_left(). Also. so a polynomial will be represented as a list of structures. ci is the coefficient of the ith term and n is the degree of the polynomial Some examples are: 5x2 + 3x + 1 12x3 – 4x 5x4 – 8x3 + 2x2 + 4x1 + 9x0 It is not necessary to write terms of the polynomials in decreasing order of degree. Each of these pairs will constitute a structure. 3.case 7 : cdll_delete_mid(). For example.10.1. case 10: exit(0). } } getch(). Also. of Information Technology . the code to manipulate doubly linked lists needs to maintain the prev fields as well as the next fields. } 3. Comparison of Linked List Variations: The major disadvantage of doubly linked lists (over singly linked lists) is that they require more space (every node has two pointer fields instead of one).10.9. In other words the two polynomials 1 + x and x + 1 are equivalent. the more chance there is for errors. The computer implementation requires implementing polynomials as a list of pairs of coefficient and exponent. A linked list structure that represents polynomials 5x4 – 8x3 + 2x2 + 4x1 + 9x0 illustrates in figure 3. or a righttoleft traversal of the list) more efficient. case 8 : cdll_display_left_right(). break.
10.h> #include <stdio. return tmp.&tmp>expo). while( 1 ) { printf ("\n Do U Want polynomial node (y/n): "). int expo. ch = getche().1. fflush(stdin). } node * create_poly (node *p ) { char ch. newnode = getnode(). struct link *next. if( p == NULL ) p = newnode.h> struct link { float coef. node *temp. else { temp = p. Single Linked List for the polynomial F(x) = 5x4 – 8x 3 + 2x 2 + 4x 1 + 9x 0 3. scanf("%d".10.start Coefficient 500 5 4 100 500 Exponent 8 100 3 200 2 200 2 300 4 1 300 400 9 0 X 400 Figure 3. printf("\n Enter Coefficient : "). temp>next = newnode. Source code for polynomial creation with help of linked list: #include <conio. node * getnode() { node *tmp. of Information Technology .h> #include <malloc. while(temp>next != NULL ) temp = temp>next. }. if(ch == 'n') break. tmp =(node *) malloc( sizeof(node) ).&tmp>coef). tmp>next = NULL.*newnode. typedef struct link node. 77 Dept. scanf("%f". } } Lecture Notes } return p. fflush(stdin). printf("\n Enter Exponent : ").1.
*poly3=NULL.h> #include <malloc. t =t > next. 3.10. printf("\n Enter Polynomial 2: "). display (poly1). poly1 = create_poly (poly1). Add them.10. } } void main() { node *poly1 = NULL . clrscr(). } 3. When we reach at the end of one of the polynomial. clrscr().(in ascendingorder of exponent)"). t > coef). node * getnode() { node *tmp. To add two polynomials follow the following steps: • • • Read two polynomials. then remaining part of the other is copied into the sum. poly2 = create_poly (poly2).*poly2 = NULL. otherwise. printf("\nEnter Second Polynomial. Source code for polynomial addition with help of linked list: #include <conio. printf("\n Enter Polynomial 1: "). typedef struct link node. display (poly2). int expo. printf("\nEnter First Polynomial. then we add the coefficients. Lecture Notes 78 Dept.(in ascendingorder of exponent)"). struct link *next.h> struct link { float coef.h> #include <stdio.. getch(). }. we copy the term of larger exponent into the sum and go on. while (t != NULL) { printf("+ %.2. Addition of Polynomials: To add two polynomials we need to scan them once. t > expo). printf("X^ %d". If we find terms with the same exponent in the two polynomials.2f".. of Information Technology .3.void display (node *p) { node *t = p. Display the resultant polynomial.
tmp>next = NULL. scanf("%f".p1>expo). while( 1 ) { printf ("\n Do U Want polynomial node (y/n): ").&tmp>expo). printf("X^ %d". ch = getche().p1>coef+p2>coef. fflush(stdin). p1 = p1>next. newnode = getnode().&tmp>coef). temp>next = newnode. node *temp. if( p == NULL ) p = newnode. return tmp. while (t != NULL) { printf("+ %. p2 = p2>next. printf("\n Enter Exponent : "). of Information Technology .node *p2) { node *newnode. fflush(stdin). } } void add_poly(node *p1. t > expo). } node * create_poly (node *p ) { char ch.tmp =(node *) malloc( sizeof(node) ). if(ch == 'n') break. t = t > next. } } return p.*newnode. while(temp>next != NULL ) temp = temp>next. if(p1>expo == p2>expo ) { printf("+ %.2f". while(1) { if( p1 == NULL  p2 == NULL ) break. t > coef).2f X ^%d". else { temp = p. } else { if(p1>expo < p2>expo) Lecture Notes 79 Dept. printf("\n Enter Coefficient : "). } void display (node *p) { node *t = p. scanf("%d".
*poly2 = NULL. ….) and R2 = (l1. l2..). poly1 = create_poly (poly1). p2 = p2>next. printf("\n Enter Polynomial 2: "). Lecture Notes 80 Dept. Let the list be L = (l0. printf( "\n Resultant Polynomial : ").p1>expo). poly2).p2>expo).. Write a “C” function to insert a node “t” before a node pointed to by “X” in a single linked list “L”.ln) is represented by a single linked list. l4. …. getch(). printf("\nEnter First Polynomial.p1>coef.2f X ^%d". } Exercise 1. of Information Technology .p1>expo). …. display (poly1). l1. } void main() { node *poly1 = NULL .2f X ^%d"... printf("\n Enter Polynomial 1: "). 3.. l3.2f X ^%d".p2>expo). Write a “C” functions to split a given list of integers represented by a single linked list into two lists in the following way. poly2 = create_poly (poly2). ln). } } while(p1 != NULL ) { printf("+ %. ln) after another ordered list M represented by a single linked list. l1.p2>coef. Write a “C” function to delete a node pointed to by “p” from a single linked list “L”.p1>coef.p2>coef. clrscr(). It is required to append the list L = (ln. clrscr()... printf(" + %..*poly3=NULL.2f X ^%d". 4. p2 = p2>next. display (poly2).. l5. l0.{ } else { } printf("+ %. p1 = p1>next.(in ascendingorder of exponent)"). Suppose that an ordered list L = (l0. …. printf("\nEnter Second Polynomial. display (poly3). The resultant lists would be R1 = (l0.. …. l1. } while(p2 != NULL ) { } printf("+ %.(in ascendingorder of exponent)"). add_poly(poly1. p1 = p1>next. 2.
13. 8.5. of Information Technology . 9. with zero being printed in place of zero elements. 6. each row in one line of output and properly formatted. The list itself is unchanged. Write “C” functions to: 1. Postcondition: The return value is the sum of all the data components of all the nodes. Consider representing a linked list of integers using arrays. The list might be empty or it might be nonempty. Implement the following function as a new function for the linked list toolkit. Postcondition: The return value is the number of occurrences of 42 in the data field of a node on the linked list. Precondition: head_ptr points to the start of a linked list. 11. 10. Precondition: head_ptr points to the start of a linked list. 7. The list might be empty or it might be nonempty. Implement the following function as a new function for the linked list toolkit. Write a “C” function to represent a sparse matrix having “m” rows and “n” columns using linked list. the function returns 0. Precondition: head_ptr points to the start of a linked list. Write a “C” function to delete the ith node from the list. 2. Write “C” functions to compute the following operations on polynomials represented as singly connected linked list of nonzero terms. Lecture Notes 81 Dept. Postcondition: The return value is true if the list has at least one occurrence of the number 42 in the data part of a node. 2. NOTE: If the list is empty. Where all sparse matrices are to be represented by linked lists. The list might be empty or it might be nonempty. 1. Write a “C” function to print a sparse matrix. Implement the following function as a new function for the linked list toolkit. 12. Evaluation of a polynomial Multiplication of two polynomials. Write a “C” function to concatenate two circular linked lists producing another circular linked list. Add two m X n sparse matrices and Multiply two m X n sparse matrices.
Memory is allocated dynamically to a data structure during execution by . What kind of list is best to answer questions such as: "What is the item at position n?" A. 1 C. 9. A runtime error always occurs when *p is evaluated. Stack D. Queue D. if it is assumed that X points to neither the first nor last element of the list? [ A ] Lecture Notes 82 Dept. C. Doublylinked lists. address of the next node B. A syntax error always occurs at compilation time. Singlylinked lists. How many null pointer/s exist in a circular double linked list? A. A. Doublylinked or singlylinked lists are equally best. D. Double Linked List C. int data. Lists implemented with an array. C. Queue C. Stack B. B.Multiple Choice Questions 1. The results are unpredictable. Interchange the first two elements of the list [ A ] A double linked list is declared as follows: struct dllist { struct dllist *fwd. Linked List B. *bwd. realloc() B. The link field in a node contains: A. Which among the following segments of code deletes the element pointed to by X from the double linked list. What happens if your program tries to read or write *p? A. Suppose that p is a pointer variable that contains the NULL pointer. D. 7. data of next node D. data of previous node [ A ] 4. malloc() C.function. A runtime error always occurs when the program finishes. data of current node [ ] [ A ] In a single linked list which operation depends on the length of the list. Add an element before the first element of the list C. 3 B. 2 D. Which among the following is a linear data structure: A. Delete the first element of the list D. all the above [ D ] 2. B. Calloc() D. all the above [ D ] 5. 8. of Information Technology . C. Which among the following is a dynamic data structure: A. all the above [ A ] 3. Delete the last element of the list B. 0 [ D ] 6. A. } Where fwd and bwd represents forward and backward links to adjacent elements of the list.
[ B ] Lecture Notes 83 Dept. X > bwd > fwd = X > fwd. start > bwd = NULL. X != NULL. ctr++) X = X > bwd. ctr++) X = X > fwd. C. X > fwd > bwd = X > bwd. D. Which among the following segment of code counts the number of elements in the double linked list. for (ctr=1.A. Which among the following segment of code deletes the element pointed to by X from the double linked list. X > bwd = X > fwd. X > bwd > fwd = NULL. X > fwd > fwd = X > fwd [ B ] 11. for (ctr=1. C. B. for (ctr=1. start = X > fwd. X > bwd > fwd = X > bwd. for (ctr=1. X > fwd != NULL. X > bwd != NULL. of Information Technology . if it is assumed that X points to the first element of the list and ctr is the variable which counts the number of elements in the list? A. [ C ] 12. if it is assumed that X points to the first element of the list and start pointer points to beginning of the list? A. X > bwd > fwd = X > bwd. X > bwd > bwd = X > bwd. X > fwd != NULL. [ A ] 13. X != NULL. start = X > fwd. C. ctr++) X = X > fwd. B. X > fwd > fwd = X > fwd 10. ctr++) X = X > fwd. if it is assumed that X points to the last element of the list? A. Which among the following segment of code deletes the element pointed to by X from the double linked list. if it is assumed that X points to the last element of the list and ctr is the variable which counts the number of elements in the list? A. for (ctr=1. B. ctr++) X = X > bwd. ctr++) X = X > bwd. D. D. for (ctr=1. X > fwd > fwd = X > bwd D. X > fwd > bwd = X > fwd C. X > bwd > bwd = X > fwd. X > fwd > bwd = X > bwd B. ctr++) X = X > bwd. X > fwd = X > bwd B. X > bwd != NULL. for (ctr=1. X > fwd > bwd = NULL. X > fwd = NULL D. X != NULL. X > bwd > bwd = X > bwd. for (ctr=1. C. X != NULL. Which among the following segment of code counts the number of elements in the double linked list. ctr++) X = X > fwd.
e neither first nor last) element of the double linked list? Assume temp pointer points to the previous position of new node. last > fwd = X. start > bwd = X. X > bwd = X > fwd. temp > bwd = X > fwd.14. X > bwd = X > fwd. Lecture Notes 84 Dept. Which among the following segment of code inserts a new node pointed by X to be inserted at the beginning of the double linked list. 16. X > fwd > bwd = X > fwd C. X > bwd = X > fwd. B. start = X. D. The start and last pointer points to beginning and end of the list respectively? A. C. X > fwd > bwd = X > bwd B. X > fwd = X > bwd. start > bwd = X. X > fwd = X > bwd B. temp > fwd = X. X >fwd = x X >fwd>bwd = temp D. X > bwd = last. X > bwd = temp. X > fwd = start. X > fwd = last. X > bwd > fwd = X > bwd. Which among the following segments of inserts a new node pointed by X to be inserted at any position (i. X > fwd = temp > fwd. Which among the following segments of inserts a new node pointed by X to be inserted at the end of the double linked list. X > fwd = X > bwd. X > fwd > fwd = X > fwd 15. A. D. C. X > fwd > bwd = X. X > fwd = start. X > bwd > bwd = X > bwd. X > bwd = X > bwd. start = X. The start pointer points to beginning of the list? [ B ] [ C ] [ D ] A. X > bwd > fwd = X > fwd. of Information Technology . temp >fwd = X.
if it is assumed that X points to the last element of the list and prev pointer points to last but one element? A. X = start > next. prev > next = X > next. free(X). free(prev). free(prev). free(X). X > next = prev> next. B. Lecture Notes 85 Dept. start = X. of Information Technology . C. } Where next represents links to adjacent elements of the list. B. prev > next = NULL. int data. D. free(X). free(prev). B. D. A single linked list is declared as follows: struct sllist { struct sllist *next. free(start). C. if it is assumed that X points to the first element of the list and start pointer points to beginning of the list? A. 18. C. if it is assumed that X points to neither the first nor last element of the list? prev pointer points to previous element. Which among the following segment of code deletes the element pointed to by X from the single linked list. start = X > next. X > next = prev > next. X = X > next. Which among the following segment of code deletes the element pointed to by X from the single linked list. prev > next = NULL. free(X). X > next = NULL. free(X). free(prev). 19. free(start). start = start > next. free(X). D X > next = prev.17. prev > next = X > next. [ A ] [ B ] [ C ] Which among the following segments of code deletes the element pointed to by X from the single linked list. A.
D. X > next = start. last > next = X > next. for (ctr=1. prev > next = X > next. X > next != NULL. X > next = last. X > next = prev. for (ctr=1. D. B. 23. if it is assumed that X points to the first element of the list and ctr is the variable which counts the number of elements in the list? [ A ] [ B ] [ C ] [ D ] A. 21. The start pointer points to beginning of the list? A. Which among the following segments of inserts a new node pointed by X to be inserted at the end of the single linked list. X > next = NULL. Which among the following segments of inserts a new node pointed by X to be inserted at any position (i. X > next = prev > next. X > next = prev > next. X > next = start > next. C. A. last > next = X. prev > next = X. The start and last pointer points to beginning and end of the list respectively? A. for (ctr=1. start > next = X. start = X D. prev > next = X. X > next = NULL. ctr) X = X > next. of Information Technology . C. X > next = start. start = X > next 22. X > next != NULL. ctr++) X = X > next. for (ctr=1. X != NULL. B. X = start.e neither first nor last) element of the single linked list? Assume prev pointer points to the previous position of new node. Lecture Notes 86 Dept. ctr) X = X > next. last > next = X. ctr++) X = X > next. B. X = prev > next.20. Which among the following segment of code inserts a new node pointed by X to be inserted at the beginning of the single linked list. D. Which among the following segment of code counts the number of elements in the single linked list. X != NULL. X > next = start. B. C. last >next = NULL. start = X C. prev > next = X > next.
of Information Technology . X > bwd > fwd = X > fwd. X > fwd > bwd = X > bwd. Which among the following segment of code deletes the element pointed to by X from the circular double linked list. A circular double linked list is declared as follows: struct cdllist { struct cdllist *fwd. D. X > bwd > bwd = start. } Where fwd and bwd represents forward and backward links to adjacent elements of the list. 26. X > fwd > fwd = X > bwd. X > bwd > fwd = X > fwd. X > fwd > fwd = X > fwd. start = start > fwd. C. X > bwd > bwd = X > fwd. start > bwd = X > fwd C. start = start > bwd.24. X > bwd > fwd = start. B. start > bwd = X > bwd D. X > bwd > bwd = X > bwd. X > fwd > fwd = start. start > bwd = X > bwd. X > bwd > fwd = X. X > bwd > fwd = X > fwd. X > bwd > fwd = X > bwd. D. *bwd. if it is assumed that X points to the first element of the list and start pointer points to beginning of the list? A. X > fwd > bwd = X > bwd. start = start > fwd. if it is assumed that X points to neither the first nor last element of the list? A. X > fwd > bwd= X > fwd. X > fwd > fwd= X > bwd. if it is assumed that X points to the last element of the list and start pointer points to beginning of the list? A. Lecture Notes 87 Dept. X > bwd > bwd = X > fwd. start > bwd = X > bwd. [ A ] [ D ] [ B ] Which among the following segments of code deletes the element pointed to by X from the circular double linked list. int data. B. Which among the following segment of code deletes the element pointed to by X from the circular double linked list. X > fwd > fwd = X > bwd. start = start > bwd. 25. X > bwd > bwd = X > bwd. C. B. X > fwd > bwd = X > fwd.
fwd = start. =X D. X > bwd = temp. [ A ] 28. for (ctr=1. start > fwd = X. Which among the following segment of code inserts a new node pointed by X to be inserted at the end of the circular double linked list. start > bwd = X. X> fwd = start. X > fwd = start > fwd. for (ctr=1. X > bwd > fwd = X > fwd.e neither first nor last) element of the circular double linked list? Assume temp pointer points to the previous position of new node. Which among the following segment of code counts the number of elements in the circular double linked list. start > fwd> fwd = X. X>fwd != start. ctr++) X = X > bwd. A. B. Which among the following segment of code inserts a new node pointed by X to be inserted at the beginning of the circular double linked list. D. Which among the following segments of inserts a new node pointed by X to be inserted at any position (i. start > bwd = X. X > bwd = start. for (ctr=1. start = X D. X > bwd = start > bwd. start > fwd> fwd = X. C. start > bwd = X. X > fwd = start > bwd. D. ctr++) X = X > fwd. X > fwd != NULL. X > fwd = start > fwd. X > fwd > bwd = X > fwd. X > fwd > bwd = X. C. X > bwd != NULL. > bwd = X. start > bwd > fwd = X. X > fwd > bwd = temp. X > fwd = start. X = start. C. X > bwd > fwd = X > bwd. ctr++) X = X > fwd. 29. X > bwd = start > bwd. start > bwd > fwd = X. start > fwd = X. temp > fwd = X. B. > bwd> fwd = X. The start pointer points to beginning of the list? A. X > bwd= start > bwd. X > fwd = X. start > bwd> fwd = X. X > bwd = start. ctr++) X = X > bwd. temp > bwd = X > fwd. of Information Technology . temp > fwd = X. X > bwd = start. start > bwd> fwd = X. if it is assumed that X and start points to the first element of the list and ctr is the variable which counts the number of elements in the list? A. for (ctr=1.27. start = X [ C ] 30. X > fwd = start. The start pointer points to beginning of the list? A. [ D ] Lecture Notes 88 Dept. X > fwd = temp > fwd. start > bwd = X. B. start = X start = X [ B ] B. X > fwd > bwd = X > bwd. X = start. X > bwd = start > bwd. X > X > start start start bwd = start > bwd. C. X > fwd = start. start > bwd > fwd = X. X != NULL. start > bwd = X.
The most accessible element is the top and the least accessible element is the bottom of the stack. 4.. “Push” is the term used to insert an element into a stack. you cannot remove elements beyond the base of the stack. The number of elements to be added should not exceed the maximum size of the stack. not in the middle. we will encounter a stack overflow condition. Figure 4. Similarly. If we attempt to add new element beyond the maximum size. Representation of Stack: Let us consider a stack with 6 elements capacity. This is called as the size of the stack.1. at the end or in the middle. • Pop: is the term used to delete an element from a stack. • Queue. the stack base remains fixed while the stack top changes as elements are added and removed. When an element is added to a stack.e. As the items can be added or removed only from the top i. the last item to be added to a stack is the first item to be removed. Two of such data structures that are useful are: • Stack. Lecture Notes 89 Dept.1.Chapter 4 Stack and Queue There are certain situations in computer science that one wants to restrict insertions and deletions so that they can take place only at the beginning or the end of the list. first out) lists. STACK: A stack is a list of elements in which an element may be inserted or deleted only at one end. we will reach a stack underflow condition. called the top of the stack. All insertions and deletions take place at the same end. “Pop” is the term used to delete an element from the stack. so the last element added to the stack will be the first element removed from the stack. at the beginning. If such is the case. the operation is performed by push(). Linear lists and arrays allow one to insert and delete elements at any place in the list i.1.e. 4. The two basic operations associated with stacks are: • Push: is the term used to insert an element into a stack. Stacks are sometimes known as LIFO (last in. of Information Technology . When a stack is created.1 shows the creation of a stack and addition of elements using push().
h> # define MAX 6 int stack[MAX]. ").").. int menu() { int ch. } void display() { int i. Lecture Notes 90 Dept.h> # include <stdlib. scanf("%d".2. of Information Technology . Source code for stack operations. printf("\n 2. int top = 0.1. if(top == 0) { printf("\n\nStack empty.2. printf("\n **********\n"). Push ").2 shows a stack initially with three elements and shows the deletion of elements using pop(). clrscr(). Quit "). Display").. Push operations on stack When an element is taken off from the stack. printf("\n 4. printf("\n 3. printf("\n 1. Figure 4.. &ch).1. printf("\n Enter your choice: "). return ch.4 4 4 3 3 3 2 2 1 11 0 TOP Empty Stack 22 11 0 Insert 11 3 TOP 33 2 TOP 1 TOP 4 22 1 11 0 Insert 22 2 1 0 Insert 33 Figure 4. the operation is performed by pop(). Pop ").h> # include <conio. TOP 33 22 11 Initial Stack 4 4 4 4 3 3 3 3 2 2 2 1 1 2 1 0 TOP 22 11 1 TOP 11 0 POP 0 TOP 0 POP POP Empty Stack Figure 4. Pop operations on stack 4. printf("\n … Stack operations using ARRAY. using array: # include <stdio.
return... do { ch = menu(). i < top. scanf("%d". of Information Technology . stack[top] = data."). printf("\n\nElements in stack:"). if(top == MAX) { printf("\n\nStack Overflow. } else { printf("\n\nEnter data: "). top = top + 1. printf("\n\nData Pushed into the stack"). } Lecture Notes 91 Dept. } while(1). switch(ch) { case 1: case 2: case 3: case 4: push()."). break. } else printf("\n\npopped element is: %d ". return. &data). } void push() { int data. break. exit(0). pop(). stack[top]). stack[i]). } getch(). void pop() { if(top == 0) { printf("\n\nStack Underflow.} else { } } return. display(). break. } } void main() { int ch. i++) printf("\t%d". for(i = 0.
printf("\n Enter data ").4. scanf("%d". void push().h> struct stack { int data. node* getnode() { node *temp. node *top = NULL.h> # include <stdlib. temp > next = NULL. node *start=NULL. return temp. void display(). typedef struct stack node.h> # include <conio. } Lecture Notes 92 Dept. void pop(). }. of Information Technology .4. } void push(node *newnode) { node *temp. Source code for stack operations.").1. top 400 data next 40 X 400 30 400 300 20 start 100 300 200 10 200 100 Figure 4.3. The linked stack looks as shown in figure 4. In a stack push and pop operations are performed at one end called top. We can perform similar operations at one end of list using top pointer.3. Linked List Implementation of Stack: We can represent a stack as a linked list.1. temp=(node *) malloc( sizeof(node)) .. return. using linked list: # include <stdio. if( newnode == NULL ) { printf("\n Stack Overflow. struct stack *next. &temp > data). Linked stack representation 4.3.
} temp = start. start = NULL. } temp > next = NULL. printf("\n\n\t Popped element is %d ". } else { while(temp > next != top) { temp = temp > next. if(top == NULL) { printf("\n\n\t\t Stack is empty ").if(start == NULL) { start = newnode. } else { temp = start. } else { temp = start. printf("\n\n\n\t\t Elements in the stack: \n"). } void pop() { node *temp. temp > next = newnode. top = newnode. top > data). } printf("\n\n\t Data pushed into stack"). printf("%5d ". top > data). free(top). temp > data). top = temp. printf("%5d ". } } void display() { node *temp. free(top). if(top == NULL) { printf("\n\n\t Stack underflow"). top = NULL. of Information Technology . if( start > next == NULL) { printf("\n\n\t Popped element is %d ". temp > data). while( temp > next != NULL) temp = temp > next. while(temp != top) { temp = temp > next. } } } Lecture Notes 93 Dept. top = newnode. return.
printf("\n **********\n").. break.char menu() { char ch. printf("\n 1. } void main() { char ch. } while( ch != '4' ). of Information Technology . z or a constant like 5. printf("\n \tStack operations using pointers. do { ch = menu(). printf("\n 3. push(newnode). printf("\n 4.2.D) Prefix: It is the form of an arithmetic notation in which we fix (place) the arithmetic operator before (pre) its two operands. The prefix notation is called as Lecture Notes 94 Dept. } 4. They are infix. printf("\n Enter your choice: "). 6 etc. printf("\n 2. ^ etc. return ch. *. postfix and prefix notations: Infix: It is the form of an arithmetic expression in which we fix (place) the arithmetic operator in between the two operands. Examples of familiar operators include +. } getch(). case '3' : display(). Algebraic Expressions: An algebraic expression is a legal combination of operators and operands. Push "). switch(ch) { case '1' : newnode = getnode(). An algebraic expression can be represented using three different notations. break. Operand is the quantity on which a mathematical operation is performed. /. case '2' : pop(). Quit "). y. Example: (A + B) * (C . node *newnode. Pop "). case '4': return. 4. Operator is a symbol which signifies a mathematical or logical operation between the operands. Display"). clrscr(). Operand may be a variable like x. ch = getche(). . "). break.
3. are not needed to designate the expression un 3. Lecture Notes 95 Dept. of Information Technology . Example: * + A B – C D Postfix: It is the form of an arithmetic expression in which we fix (place) the arithmetic operator after (post) its two operands. Scan the infix expression from left to right. Conversion from infix to postfix: Procedure to convert from infix expression to postfix expression is as follows: 1. 6. the following in the order of precedence (highest to lowest): OPERATOR PRECEDENCE VALUE Highest 3 *.3. The postfix notation is called as suffix notation and is also referred to reverse polish notation. 2. Converting expressions using Stack: Let us convert the expressions from one type to another. 5. .  Lowest 1 Exponentiation ($ or ↑ or ^) 4. *. 2.* The three important features of postfix expression are: 1. These can be done as follows: 1.1. 4. While evaluating the postfix expression the priority of the operators is no longer relevant. We consider five binary operations: +.polish notation (due to the polish mathematician Jan Lukasiewicz in the year 1920). Infix to postfix Infix to prefix Postfix to infix Postfix to prefix Prefix to infix Prefix to postfix 4. 3. The operands maintain the same order as in the equivalent infix expression. 2. push it onto the stack. Example: A B + C D . / and $ or ↑ (exponentiation). then place directly in the postfix expression (output). / Next highest 2 +. The parentheses ambiguously. b) If the scanned symbol is an operand. For these binary operations. a) If the scanned symbol is left parenthesis.
of Information Technology . SYMBOL POSTFIX STRING a a + a + b ab + Lecture Notes STACK 96 REMARKS Dept. Example 1: Convert ((A – (B + C)) * D) ↑ (E + F) infix expression to postfix form: SYMBOL POSTFIX STRING STACK ( ( ( (( REMARKS A A ((  A (( ( A ((( B AB ((( + AB (((+ C ABC (((+ ) ABC+ (( ) ABC+ ( * ABC+ (* D ABC+D (* ) ABC+D* ↑ ABC+D* ↑ ( ABC+D* ↑( E ABC+D*E ↑( + ABC+D*E ↑(+ F ABC+D*EF ↑(+ ) ABC+D*EF+ ↑ ABC+D*EF+↑ The input is now empty.c) If the symbol scanned is a right parenthesis. push the scanned operator onto the stack. then go on popping all the items from the stack and place them in the postfix expression till we get the matching left parenthesis. End of string Example 2: Convert a + b * c + (d * e + f) * g the infix expression into postfix form. d) If the scanned symbol is an operator. Pop the output symbols from the stack until it is empty. if and only if the precedence of the operator which is on the top of the stack is greater than (or greater than or equal) to the precedence of the scanned operator and push the scanned operator onto the stack otherwise. then go on removing all the operators from the stack and place them in the postfix expression.
Pop the output symbols from the stack until it is empty.* ab +* c abc +* + abc*+ + ( abc*+ +( d abc*+d +( * abc*+d +(* e abc*+de +(* + abc*+de* +(+ f abc*+de*f +(+ ) abc*+de*f+ + * abc*+de*f+ +* g abc*+de*f+g +* End of string abc*+de*f+g*+ The input is now empty. of Information Technology . SYMBOL POSTFIX STRING STACK A A + A + B AB + * AB +* C ABC +*  ABC*+  D ABC*+D  REMARKS / ABC*+D / E ABC*+DE / * ABC*+DE/ * H End of string ABC*+DE/H * The input is now empty. Example 3: Convert the following infix expression A + B * C – D / E * H into its equivalent postfix expression. ABC*+DE/H* Example 4: Convert the following infix expression A + (B * C – (D / E ↑ F) * G) * H into its equivalent postfix expression. SYMBOL POSTFIX STRING A A + A Lecture Notes STACK REMARKS + 97 Dept. Pop the output symbols from the stack until it is empty.
char infix[50].3. k ++) { if(op_at_stack == operators[k]) pv2 = priority_value[k]. } for(k = 0. /* priority value of op */ int pv2.( A +( B AB +( * AB +(* C ABC +(*  ABC* +( ( ABC* +(( D ABC*D +(( / ABC*D +((/ E ABC*DE +((/ ↑ ABC*DE +((/↑ F ABC*DEF +((/↑ ) ABC*DEF↑/ +( * ABC*DEF↑/ +(* G ABC*DEF↑/G +(* ) ABC*DEF↑/G* + * ABC*DEF↑/G* +* H ABC*DEF↑/G*H +* End of string ABC*DEF↑/G*H*+ The input is now empty. if( op_at_stack == '(' ) return 0. /* operator stack */ int lesspriority(char op. '/'. '(' }. '*'. char opstack[50]. of Information Technology . else return 0. k ++) { if(op == operators[k]) pv1 = priority_value[k].0.2.3. } if(pv1 < pv2) return 1.2. int pv1. k < 6. /* priority value of op_at_stack */ char operators[] = {'+'.1. int priority_value[] = {0. } Lecture Notes 98 Dept. '%'. Pop the output symbols from the stack until it is empty.1. for(k = 0. '^'. k < 6. j. Program to convert an infix to postfix expression: # include <string. int i.h> char postfix[50]. 4. char op_at_stack) { int k. top = 0. ''.4}.
of Information Technology .void push(char op) /* op . j++. default : postfix[j] = ch. } /* pop until '(' comes */ } void main() { char ch. clrscr(). gets(infix). while( (ch=infix[i++]) != ‘\0’) { switch(ch) { case ' ' : break. } } pop() { while(opstack[top] != '(' ) { postfix[j] = opstack[top]. Lecture Notes /* check priority and push */ 99 Dept. printf("\n Enter Infix Expression : "). case ')' : pop(). break. j++. j++.operator */ { if(top == 0) /* before pushing the operator { 'op' into the stack check priority opstack[top] = op. opstack[top1]) == 1 && top > 0) { postfix[j] = opstack[top]. /* pushing onto stack */ top++. break. j++. then pop the operator from stack } then push into postfix string else else push op onto stack itself */ { if(op != '(' ) { while(lesspriority(op. } } opstack[top] = op. of op with top of opstack if less top++. } } while(top >= 0) { postfix[j] = opstack[top]. case '(' : case '+' : case '' : case '*' : case '/' : case '^' : case '%' : push(ch).
Example 2: Convert the infix expression (A + B) * (C . getch(). SYMBOL PREFIX STRING STACK C C  C  B BC  + BC + A ABC + End of string +ABC REMARKS The input is now empty. printf("\n Infix Expression : %s ". Conversion from infix to prefix: The precedence rules for converting an expression from infix to prefix are identical. 100 Dept. printf("\n Postfix Expression : %s ". Pop the output symbols from the stack until it is empty. SYMBOL PREFIX STRING STACK ) REMARKS ) D D )  D ) C CD ) ( CD * CD * ) CD *) B BCD *) + BCD *)+ A ABCD *)+ ( +AB–CD * End of string Lecture Notes *+AB–CD The input is now empty. of Information Technology . postfix).} postfix[j] = '\0'. The prefix form of a complex expression is not the mirror image of the postfix form.3.C into prefix expression. infix). Pop the output symbols from the stack until it is empty.3. Example 1: Convert the infix expression A + B .D) into prefix expression. } 4. The only change from postfix conversion is that traverse the expression from right to left and the operator is placed before the operands rather than after them.
of Information Technology . SYMBOL PREFIX STRING STACK ) ) H H ) + H )+ G GH )+ ( +GH / +GH / F F+GH / / F+GH // E EF+GH // + //EF+GH + D D//EF+GH +  D//EF+GH + C CD//EF+GH + * CD//EF+GH +* B BCD//EF+GH +* ↑ BCD//EF+GH +*↑ A ABCD//EF+GH +*↑ End of string 4. else { for(k = j + 1. } Lecture Notes 101 Dept.1]. prefix[0] = ch. k > 0. char opstack[50]. k) prefix[k] = prefix[k .h> char prefix[50]. int j. if(j == 0) prefix[0] = ch. top = 0. Pop the output symbols from the stack until it is empty.Example 3: Convert the infix expression A ↑ B * C – D + E / F / (G + H) into prefix expression. } j++. /* operator stack */ void insert_beg(char ch) { int k. Program to convert an infix to prefix expression: # include <conio. char infix[50].3.4. REMARKS +*↑ABCD//EF+GH The input is now empty.h> # include <string.
0. Lecture Notes 102 Dept. int pv1. 3. printf("\n Enter Infix Expression : "). char op_at_stack) { int k. 1. 4}. k < 6. /* priority value of op */ int pv2. i = 0. opstack[top1]) == 1 && top > 0) { insert_beg(opstack[top]). for(k = 0. } */ /* pop until ')' comes. k ++) { if(op == operators[k]) pv1 = priority_value[k]. top++. int priority_value[] = {0. 2. else return 0. clrscr(). k < 6. if(op_at_stack == ')' ) return 0. */ void main() { char ch. '/'. } void push(char op) /* op – operator */ { if(top == 0) { opstack[top] = op. k ++) { if( op_at_stack == operators[k] ) pv2 = priority_value[k]. int l. ''. /* pushing onto stack void pop() { while(opstack[top] != ')') insert_beg(opstack[top]). of Information Technology . top++. /* priority value of op_at_stack */ char operators[] = {'+'. } for(k = 0.int lesspriority(char op. } } } } opstack[top] = op. '%'. } if(pv1 < pv2) return 1. 1. } else { if(op != ')') { /* before pushing the operator 'op' into the stack check priority of op with top of operator stack if less pop the operator from stack then push into postfix string else push op onto stack itself */ while(lesspriority(op. '*'. ')'}. '^'.
infix). If the scanned symbol is an operator. 4. printf("\n Prefix Expression : %s ". /* check priority and push */ Conversion from postfix to infix: Procedure to convert postfix expression to infix expression is as follows: 1. then push it onto the stack. break. Repeat steps 2 and 3 till the end of the expression. If the scanned symbol is an operand. prefix). of Information Technology . Lecture Notes 103 Dept. Example: Convert the following postfix expression A B C * D E F ^ / G * . pop two symbols from the stack and create it as a string by placing the operator in between the operands and push it onto the stack. l = strlen(infix).3. getch(). 3. j++. 4. while(l > 0) { ch = infix[l]. case ')' : case '+' : case '' : case '*' : case '/' : case '^' : case '%' : push(ch). printf("\n Infix Expression : %s ". switch(ch) { case ' ' : break. } } while( top > 0 ) { insert_beg( opstack[top] ). 2. } prefix[j] = '\0'. break.} gets(infix). case '(' : pop().5.H * + into its equivalent infix expression. Scan the postfix expression from left to right. default : insert_beg(ch).
Symbol
Stack
Remarks
A
A
B
A
B
C
A
B
*
A
(B*C)
D
A
(B*C)
D
E
A
(B*C)
D
E
F
A
(B*C)
D
E
^
A
(B*C)
D
(E^F)
/
A
(B*C)
(D/(E^F))
G
A
(B*C)
(D/(E^F))
*
A
(B*C)
((D/(E^F))*G)

A
((B*C) – ((D/(E^F))*G))
H
A
((B*C) – ((D/(E^F))*G))
*
A
(((B*C) – ((D/(E^F))*G)) * H)
+
(A + (((B*C) – ((D/(E^F))*G)) * H))
End of
string
Push B
C
Push C
Pop two operands and place the
operator in between the operands and
push the string.
Push D
Push E
F
Push F
Pop two operands and place the
operator in between the operands and
push the string.
Pop two operands and place the
operator in between the operands and
push the string.
G
Push G
Pop two operands and place the
operator in between the operands and
push the string.
Pop two operands and place the
operator in between the operands and
push the string.
H
Push H
Pop two operands and place the
operator in between the operands and
push the string.
The input is now empty. The string formed is infix.
4.3.6.
#
#
#
#
Push A
Program to convert postfix to infix expression:
include <stdio.h>
include <conio.h>
include <string.h>
define MAX 100
void pop (char*);
void push(char*);
char stack[MAX] [MAX];
int top = 1;
Lecture Notes
104
Dept. of Information Technology
void main()
{
char s[MAX], str1[MAX], str2[MAX], str[MAX];
char s1[2],temp[2];
int i=0;
clrscr( ) ;
printf("\Enter the postfix expression; ");
gets(s);
while (s[i]!='\0')
{
if(s[i] == ' ' )
/*skip whitespace, if any*/
i++;
if (s[i] == '^'  s[i] == '*' s[i] == ''  s[i] == '+'  s[i] == '/')
{
pop(str1);
pop(str2);
temp[0] ='(';
temp[1] ='\0';
strcpy(str, temp);
strcat(str, str2);
temp[0] = s[i];
temp[1] = '\0';
strcat(str,temp);
strcat(str, str1);
temp[0] =')';
temp[1] ='\0';
strcat(str,temp);
push(str);
}
else
{
temp[0]=s[i];
temp[1]='\0';
strcpy(s1, temp);
push(s1);
}
i++;
}
printf("\nThe Infix expression is: %s", stack[0]);
}
void pop(char *a1)
{
strcpy(a1,stack[top]);
top;
}
void push (char*str)
{
if(top == MAX  1)
printf("\nstack is full");
else
{
top++;
strcpy(stack[top], str);
}
}
Lecture Notes
105
Dept. of Information Technology
4.3.7.
Conversion from postfix to prefix:
Procedure to convert postfix expression to prefix expression is as follows:
1.
Scan the postfix expression from left to right.
2.
If the scanned symbol is an operand, then push it onto the stack.
3.
If the scanned symbol is an operator, pop two symbols from the stack
and create it as a string by placing the operator in front of the operands
and push it onto the stack.
5.
Repeat steps 2 and 3 till the end of the expression.
Example:
Convert the following postfix expression A B C * D E F ^ / G *  H * + into its
equivalent prefix expression.
Symbol
Stack
A
A
B
A
B
C
A
B
*
A
*BC
D
A
*BC
D
E
A
*BC
D
E
F
A
*BC
D
E
^
A
*BC
D
/
A
*BC
/D^EF
G
A
*BC
/D^EF
*
A
*BC
*/D^EFG

A
 *BC*/D^EFG
H
A
 *BC*/D^EFG
*
A
* *BC*/D^EFGH
+
+A**BC*/D^EFGH
End of
string
Remarks
Push A
Push B
C
Push C
Pop two operands and place the operator in
front the operands and push the string.
Push D
Push E
F
Push F
Pop two operands and place the operator in
front the operands and push the string.
^EF
Pop two operands and place the operator in
front the operands and push the string.
G
Push G
Pop two operands and place the operator in
front the operands and push the string.
Pop two operands and place the operator in
front the operands and push the string.
H
Push H
Pop two operands and place the operator in
front the operands and push the string.
The input is now empty. The string formed is prefix.
Lecture Notes
106
Dept. of Information Technology
4.3.8.
Program to convert postfix to prefix expression:
# include <conio.h>
# include <string.h>
#define MAX 100
void pop (char *a1);
void push(char *str);
char stack[MAX][MAX];
int top =1;
main()
{
}
char s[MAX], str1[MAX], str2[MAX], str[MAX];
char s1[2], temp[2];
int i = 0;
clrscr();
printf("Enter the postfix expression; ");
gets (s);
while(s[i]!='\0')
{
/*skip whitespace, if any */
if (s[i] == ' ')
i++;
if(s[i] == '^'  s[i] == '*'  s[i] == ''  s[i]== '+'  s[i] == '/')
{
pop (str1);
pop (str2);
temp[0] = s[i];
temp[1] = '\0';
strcpy (str, temp);
strcat(str, str2);
strcat(str, str1);
push(str);
}
else
{
temp[0] = s[i];
temp[1] = '\0';
strcpy (s1, temp);
push (s1);
}
i++;
}
printf("\n The prefix expression is: %s", stack[0]);
void pop(char*a1)
{
if(top == 1)
{
printf("\nStack is empty");
return ;
}
else
{
strcpy (a1, stack[top]);
top;
}
}
Lecture Notes
107
Dept. of Information Technology
of Information Technology . If the scanned symbol is an operand. Scan the prefix expression from right to left (reverse order). 3.1) printf("\nstack is full"). else { top++. 4.9. Push C B Push B Pop two operands and place the operator in front the operands and push the string. Example: Convert the following prefix expression + A * . } } 4. str).3. strcpy(stack[top]. Conversion from prefix to infix: Procedure to convert prefix expression to infix expression is as follows: 1. Symbol Stack Remarks H H G H G F H G F E H G F ^ H G (E^F) D H G (E^F) / H G (D/(E^F)) * H ((D/(E^F))*G) C H ((D/(E^F))*G) C B H ((D/(E^F))*G) C * H ((D/(E^F))*G) (B*C)  H ((B*C)((D/(E^F))*G)) Lecture Notes Push H Push G Push F E Push E Pop two operands and place the operator in between the operands and push the string. then push it onto the stack. 2.void push (char *str) { if(top == MAX . D Push D Pop two operands and place the operator in between the operands and push the string. If the scanned symbol is an operator. Pop two operands and place the operator in front the operands and push the 108 Dept. Repeat steps 2 and 3 till the end of the expression. pop two symbols from the stack and create it as a string by placing the operator in between the operands and push it onto the stack.* B C * / D ^ E F G H into its equivalent infix expression. Pop two operands and place the operator in between the operands and push the string.
3. char s1[2].temp). 4. temp[1] ='\0'. gets(s). Lecture Notes 109 Dept.10. strcpy(s1. temp[0] =')'. void main() { char s[MAX]. temp[0] = s[i]. clrscr( ) . temp). str[MAX].h> # define MAX 100 void pop (char*). temp). if (s[i] == '^'  s[i] == '*' s[i] == ''  s[i] == '+'  s[i] == '/') { pop(str1). printf("\Enter the prefix expression. str1[MAX]. push(str). The input is now empty. while (s[i]!='\0') { /*skip whitespace. The string formed is infix. temp[1] = '\0'. strrev(s). strcpy(str. strcat(str. Program to convert prefix to infix expression: # include <string. strcat(str.temp[2]. Pop two operands and place the operator in front the operands and push the string. strcat(str. temp[1]='\0'.string. push(s1). strcat(str. str1). * (((B*C)((D/(E^F))*G))*H) A (((B*C)((D/(E^F))*G))*H) + (A+(((B*C)((D/(E^F))*G))*H)) End of string A Push A Pop two operands and place the operator in front the operands and push the string. of Information Technology . int top = 1. void push(char*). str2). int i=0. "). if any*/ if(s[i] == ' ' ) i++. pop(str2). temp[0] ='('.temp). temp[1] ='\0'. } else { temp[0]=s[i]. char stack[MAX] [MAX]. str2[MAX].
Repeat steps 2 and 3 till the end of the expression. str).* B C * / D ^ E F G H into its equivalent postfix expression. } } printf("\nThe infix expression is: %s". Example: Convert the following prefix expression + A * . else { top++.3. Conversion from prefix to postfix: Procedure to convert prefix expression to postfix expression is as follows: 1. Symbol Stack H H G H G F H G F E H G F ^ H G EF^ D H G EF^ Lecture Notes Remarks Push H Push G Push F E Push E Pop two operands and place the operator after the operands and push the string. strcpy(stack[top]. then push it onto the stack. 2. top. of Information Technology . stack[0]). 3. Scan the prefix expression from right to left (reverse order).11.1) printf("\nstack is full"). } void push (char*str) { if(top == MAX .} i++.stack[top]). If the scanned symbol is an operator. pop two symbols from the stack and create it as a string by placing the operator after the operands and push it onto the stack. D Push D 110 Dept. void pop(char *a1) { strcpy(a1. 4. If the scanned symbol is an operand. } } 4.
if(s[i] == '^'  s[i] == '*'  s[i] == ''  s[i]== '+'  s[i] == '/') { pop (str1). push(str). char stack[MAX][MAX]. ").str2). pop (str2). int i = 0. strcpy(str. Pop two operands and place the operator after the operands and push the string. temp[0] = s[i].h> # include <conio. Pop two operands and place the operator after the operands and push the string.Pop two operands and place the operator after the operands and push the string. printf("Enter the prefix expression. strrev(s). int top =1. temp[1] = '\0'.12.h> # include <string. Push C B Push B Pop two operands and place the operator after the operands and push the string. str2[MAX]. } Lecture Notes 111 Dept. strcat (str1. Program to convert prefix to postfix expression: # include <stdio. while(s[i]!='\0') { if (s[i] == ' ') /*skip whitespace. 4. temp[2]. The input is now empty. strcat(str1. The string formed is postfix. str[MAX]. clrscr().h> #define MAX 100 void pop (char *a1).3. char s1[2]. void push(char *str). / H G * H DEF^/G* C H DEF^/G* C B H DEF^/G* C * H DEF^/G* BC*  H BC*DEF^/G* * BC*DEF^/G*H* A BC*DEF^/G*H* + ABC*DEF^/G*H*+ End of string DEF^/ Pop two operands and place the operator after the operands and push the string. str1[MAX]. temp). of Information Technology . str1). if any */ i++. gets (s). A Push A Pop two operands and place the operator after the operands and push the string. void main() { char s[MAX].
strcpy(stack[top]. the operator is applied to the two numbers that are popped from the stack and the result is pushed onto the stack. 2. Example 1: Evaluate the postfix expression: 6 5 2 3 + 8 * + 3 + * SYMBOL OPERAND 1 OPERAND 2 VALUE STACK 6 6 5 6. 3 + Lecture Notes 2 3 5 6. so 3 and 2 are popped from the stack and their sum 5. } printf("\nThe postfix expression is: %s". } } void push (char *str) { if(top == MAX . 5. 5. str). is pushed Dept. When an expression is given in postfix notation. this is our obvious advantage. Evaluation of postfix expression: The postfix expression is evaluated easily by the use of a stack. top. return . strcpy (s1. } i++. 5.4. 5 112 REMARKS The first four symbols are placed on the stack. 5 2 6. 2 3 6. there is no need to know any precedence rules. temp). of Information Technology . stack[0]). When a number is seen. } else { strcpy (a1. temp[1] = '\0'. stack[top]). else { top++. when an operator is seen.else { temp[0] = s[i].1) printf("\nstack is full"). } } 4. it is pushed onto the stack. } void pop(char*a1) { if(top == 1) { printf("\nStack is empty"). push (s1). Next a ‘+’ is read.
7 * 1 7 7 7 2 1 7 7 7. } Lecture Notes 113 Dept.h> # define MAX 20 int isoperator(char ch) { if(ch == '+'  ch == ''  ch == '*'  ch == '/'  ch == '^') return 1. 8 2 6 5 1 1. a ‘*’ is seen and 48 and 6 are popped. 2 3 6. 3 8 6 5 1 1. 2. 3 + 49 3 52 52 Program to evaluate a postfix expression: # include <conio. 2 / 8 2 4 1.8 2 3 5 6. 8 * 5 8 40 6.h> # include <math. ‘+’ pops 3 and 45 and pushes 45 + 3 = 48 is pushed Finally. so 8 and 5 are popped as 8 * 5 = 40 is pushed Next. 3. 45 3 5 40 45 6. OPERAND 1 OPERAND 2 VALUE STACK 6 6 2 6. of Information Technology .1. 3 + 45 3 48 6.4. 45. 48 * 6 48 288 288 Next 8 is pushed Now a ‘*’ is seen. else return 0.3 8 2 / + * 2 ↑ 3 + SYMBOL 4. 5. 2 ↑ 7 2 49 49 3 7 2 49 49. a ‘+’ is seen. 4 + 3 4 7 1. the result 6 * 48 = 288 is pushed Example 2: Evaluate the following postfix expression: 6 2 3 + . 5. so 40 and 5 are popped and 40 + 5 = 45 is pushed Now. 3. 3. 3 is pushed Next. 3 + 2 3 5 6. 5  6 5 1 1 3 6 5 1 1. 8. 5. 40 + 5 40 45 6.
void main(void) { char postfix[MAX]. case '^': res = pow(val1. } printf("\n Values of %s is : %f ". while((ch = postfix[i]) != '\0') { if(isoperator(ch) == 1) { val2 = val_stack[top]. break. int val. break. switch(ch) { case '+': res = val1 + val2. scanf("%s". Stack is used by compilers to check for balancing of parentheses. 5. Applications of stacks: 1.val2. break. clrscr(). char ch. val_stack[0] ). Stack is used to evaluate a postfix expression. brackets and braces. 2. top = 0. float val_stack[MAX]. 4. printf("\n Enter a postfix expression: "). int i = 0. val2). val1. During a function call the return address and arguments are pushed onto a stack and on return they are popped off.5. /*convert character digit to integer digit */ top++. } val_stack[top] = res. break. i++. case '*': res = val1 * val2. getch(). case '': res = val1 . } 4. In recursion. val1 = val_stack[top].postfix. Stack is used to convert an infix expression into postfix/prefix form. } else val_stack[top] = ch48. all intermediate arguments and return values are stored on the processor’s stack. 3. postfix). break. res. val2. case '/': res = val1 / val2. Lecture Notes 114 Dept. of Information Technology .
4.6.
Queue:
A queue is another special kind of list, where items are inserted at one end called the
rear and deleted at the other end called the front. Another name for a queue is a
“FIFO” or “Firstinfirstout” list.
The operations for a queue are analogues to those for a stack, the difference is that the
insertions go at the end of the list, rather than the beginning. We shall use the
following operations on queues:
•
enqueue: which inserts an element at the end of the queue.
•
dequeue: which deletes an element at the start of the queue.
4.6.1.
Representation of Queue:
Let us consider a queue, which can hold maximum of five elements. Initially the queue
is empty.
0
1
2
3
4
Q u e u e E mp t y
F RO NT = RE A R = 0
F R
Now, insert 11 to the queue. Then queue status will be:
0
1
2
3
4
RE A R = RE A R + 1 = 1
F RO NT = 0
11
F
R
Next, insert 22 to the queue. Then the queue status is:
0
1
11
22
F
2
3
4
RE A R = RE A R + 1 = 2
F RO NT = 0
R
Again insert another element 33 to the queue. The status of the queue is:
0
1
2
11
22
33
F
Lecture Notes
3
4
RE A R = RE A R + 1 = 3
F RO NT = 0
R
115
Dept. of Information Technology
Now, delete an element. The element deleted is the element at the front of the queue.
So the status of the queue is:
0
1
2
22
33
F
3
4
RE A R = 3
F RO NT = F R O NT + 1 = 1
R
Again, delete an element. The element to be deleted is always pointed to by the FRONT
pointer. So, 22 is deleted. The queue status is as follows:
0
1
2
3
4
RE A R = 3
F RO NT = F R O NT + 1 = 2
33
F
R
Now, insert new elements 44 and 55 into the queue. The queue status is:
0
1
2
33
3
4
44
55
F
RE A R = 5
F RO NT = 2
R
Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as
the rear crossed the maximum size of the queue (i.e., 5). There will be queue full
signal. The queue status is as follows:
0
1
2
33
3
4
44
55
F
RE A R = 5
F RO NT = 2
R
Now it is not possible to insert an element 66 even though there are two vacant
positions in the linear queue. To over come this problem the elements of the queue are
to be shifted towards the beginning of the queue so that it creates vacant position at
the rear end. Then the FRONT and REAR are to be adjusted properly. The element 66
can be inserted at the rear end. After this operation, the queue status is as follows:
0
1
2
33
44
55
F
3
4
RE A R = 4
F RO NT = 0
66
R
This difficulty can overcome if we treat queue position with index 0 as a position that
comes after position with index 4 i.e., we treat the queue as a circular queue.
Lecture Notes
116
Dept. of Information Technology
4.6.2.
Source code for Queue operations using array:
In order to create a queue we require a one dimensional array Q(1:n) and two
variables front and rear. The conventions we shall adopt for these two variables are
that front is always 1 less than the actual front of the queue and rear always points to
the last element in the queue. Thus, front = rear if and only if there are no elements in
the queue. The initial condition then is front = rear = 0. The various queue operations
to perform creation, deletion and display the elements in a queue are as follows:
1.
insertQ(): inserts an element at the end of queue Q.
2.
deleteQ(): deletes the first element of Q.
3.
displayQ(): displays the elements in the queue.
# include <conio.h>
# define MAX 6
int Q[MAX];
int front, rear;
void insertQ()
{
int data;
if(rear == MAX)
{
printf("\n Linear Queue is full");
return;
}
else
{
printf("\n Enter data: ");
scanf("%d", &data);
Q[rear] = data;
rear++;
printf("\n Data Inserted in the Queue ");
}
}
void deleteQ()
{
if(rear == front)
{
printf("\n\n Queue is Empty..");
return;
}
else
{
printf("\n Deleted element from Queue is %d", Q[front]);
front++;
}
}
void displayQ()
{
int i;
if(front == rear)
{
printf("\n\n\t Queue is Empty");
return;
}
else
{
printf("\n Elements in Queue are: ");
for(i = front; i < rear; i++)
Lecture Notes
117
Dept. of Information Technology
{
printf("%d\t", Q[i]);
}
}
}
int menu()
{
int ch;
clrscr();
printf("\n \tQueue operations using ARRAY..");
printf("\n **********\n");
printf("\n 1. Insert ");
printf("\n 2. Delete ");
printf("\n 3. Display");
printf("\n 4. Quit ");
printf("\n Enter your choice: ");
scanf("%d", &ch);
return ch;
}
void main()
{
int ch;
do
{
ch = menu();
switch(ch)
{
case 1:
insertQ();
break;
case 2:
deleteQ();
break;
case 3:
displayQ();
break;
case 4:
return;
}
getch();
} while(1);
}
4.6.3.
Linked List Implementation of Queue:
We can represent a queue as a linked list. In a queue data is deleted from the front end
and inserted at the rear end. We can perform similar operations on the two ends of a
list. We use two pointers front and rear for our linked queue implementation.
The linked queue looks as shown in figure 4.4:
front
rear
100
400
10
100
200
20
300
200
30
400
300
40
X
400
Figure 4.4. Linked Queue representation
Lecture Notes
118
Dept. of Information Technology
6. } Lecture Notes 119 Dept. node* getnode() { node *temp. rear = newnode. newnode = getnode(). Source code for queue operations using linked list: # include <stdlib. rear = newnode. }. node *front = NULL. return. temp > data).. temp = (node *) malloc(sizeof(node)) . return temp. typedef struct queue node. } void insertQ() { node *newnode. } temp = front."). scanf("%d". free(temp). front = front > next. } if(front == NULL) { front = newnode. node *rear = NULL. &temp > data). } void deleteQ() { node *temp. return. if(newnode == NULL) { printf("\n Queue Full").h> struct queue { int data. printf("\n Enter data ").4. } else { rear > next = newnode. } printf("\n\n\t Data Inserted into the Queue.h> # include <conio. if(front == NULL) { printf("\n\n\t Empty Queue.4. temp > next = NULL.. of Information Technology . struct queue *next."). printf("\n\n\t Deleted element from queue is %d ".
void displayQ()
{
node *temp;
if(front == NULL)
{
printf("\n\n\t\t Empty Queue ");
}
else
{
temp = front;
printf("\n\n\n\t\t Elements in the Queue are: ");
while(temp != NULL )
{
printf("%5d ", temp > data);
temp = temp > next;
}
}
}
char menu()
{
char ch;
clrscr();
printf("\n \t..Queue operations using pointers.. ");
printf("\n\t **********\n");
printf("\n 1. Insert ");
printf("\n 2. Delete ");
printf("\n 3. Display");
printf("\n 4. Quit ");
printf("\n Enter your choice: ");
ch = getche();
return ch;
}
void main()
{
char ch;
do
{
ch = menu();
switch(ch)
{
case '1' :
insertQ();
break;
case '2' :
deleteQ();
break;
case '3' :
displayQ();
break;
case '4':
return;
}
getch();
} while(ch != '4');
}
Lecture Notes
120
Dept. of Information Technology
4.7.
Applications of Queue:
1.
It is used to schedule the jobs to be processed by the CPU.
2.
When multiple users send print jobs to a printer, each printing job is kept in
the printing queue. Then the printer prints those jobs according to first in
first out (FIFO) basis.
3.
Breadth first search uses a queue data structure to find an element from a
graph.
4.8.
Circular Queue:
A more efficient queue representation is obtained by regarding the array Q[MAX] as
circular. Any number of items could be placed on the queue. This implementation of a
queue is called a circular queue because it uses its storage array as if it were a circle
instead of a linear list.
There are two problems associated with linear queue. They are:
•
Time consuming: linear time to be spent in shifting the elements to the
beginning of the queue.
•
Signaling queue full: even if the queue is having vacant position.
For example, let us consider a linear queue status as follows:
0
1
2
33
3
4
44
55
F
RE A R = 5
F RO NT = 2
R
Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as
the rear crossed the maximum size of the queue (i.e., 5). There will be queue full
signal. The queue status is as follows:
0
1
2
33
F
3
4
44
55
RE A R = 5
F RO NT = 2
R
This difficulty can be overcome if we treat queue position with index zero as a position
that comes after position with index four then we treat the queue as a circular queue.
In circular queue if we reach the end for inserting elements to it, it is possible to insert
new elements if the slots at the beginning of the circular queue are empty.
Lecture Notes
121
Dept. of Information Technology
4.8.1.
Representation of Circular Queue:
Let us consider a circular queue, which can hold maximum (MAX) of six elements.
Initially the queue is empty.
F
R
0
5
Queue
MAX =
F RO NT
C O U NT
1
4
E mp t y
6
= RE A R = 0
= 0
2
3
C irc u l ar Q u e u e
Now, insert 11 to the circular queue. Then circular queue status will be:
F
0
5
R
11
F RO NT = 0
RE A R = ( RE A R + 1) % 6 = 1
C O U NT = 1
1
4
2
3
C irc u l ar Q u e u e
Insert new elements 22, 33, 44 and 55 into the circular queue. The circular queue
status is:
F
R
0
5
11
4
22
55
44
1
FRONT = 0
REAR = (REAR + 1) % 6 = 5
COUNT = 5
33
3
2
Circular Queue
Lecture Notes
122
Dept. of Information Technology
Now, delete an element. The element deleted is the element at the front of the circular
queue. So, 11 is deleted. The circular queue status is as follows:
R
0
5
F
4
22
55
44
F RO NT = (F R O NT + 1) % 6 = 1
RE A R = 5
C O U NT = C O U NT  1 = 4
1
33
2
3
C irc u l ar Q u e u e
Again, delete an element. The element to be deleted is always pointed to by the FRONT
pointer. So, 22 is deleted. The circular queue status is as follows:
R
0
5
4
F RO NT = (F R O NT + 1) % 6 = 2
RE A R = 5
C O U NT = C O U NT  1 = 3
1
55
44
33
F
2
3
C irc u l ar Q u e u e
Again, insert another element 66 to the circular queue. The status of the circular queue
is:
R
0
5
66
4
1
55
44
3
F RO NT = 2
RE A R = ( RE A R + 1) % 6 = 0
C O U NT = C O U NT + 1 = 4
33
2
F
C irc u l ar Q u e u e
Lecture Notes
123
Dept. of Information Technology
"). rear = (rear + 1) % MAX. void insertCQ() { int data.8. The circular queue status is: 0 5 66 4 77 88 55 44 3 1 F RO NT = 2. as COUNT = MAX we cannot add the element to circular queue.Now. rear = 0. count = 0. scanf("%d". 4. insert new elements 77 and 88 into the circular queue. } } void deleteCQ() { if(count == 0) { printf("\n\nCircular Queue is Empty. CQ[front]). if we insert an element to the circular queue. &data). front = (front + 1) % MAX. the circular queue is full. So. } else { printf("\n Enter data: "). Source code for Circular Queue operations.h> # include <conio. using array: # include <stdio. } else { printf("\n Deleted element from Circular Queue is %d ". count ++. front = 0. printf("\n Data Inserted in the Circular Queue "). RE A R = 2 RE A R = RE A R % 6 = 2 C O U NT = 6 33 2 R F C irc u l ar Q u e u e Now. if(count == MAX) { printf("\n Circular Queue is Full"). } } Lecture Notes 124 Dept. of Information Technology .2.h> # define MAX 6 int int int int CQ[MAX].. count . CQ[rear] = data.
void displayCQ() { int i."). printf("\n 1. break. printf("\n Enter Your Choice: "). } } } int menu() { int ch. Display"). } void main() { int ch. j != 0. do { ch = menu(). j) { printf("%d\t". } while(1). printf("\n 2. of Information Technology . CQ[i]). deleteCQ(). break. if(count == 0) { printf("\n\n\t Circular Queue is Empty "). } else { printf("\n Elements in Circular Queue are: "). printf("\n **********\n"). Insert "). printf("\n \t Circular Queue Operations using ARRAY. clrscr(). printf("\n 3. return.. Delete "). j. i = (i + 1) % MAX. for(i = front. j = count. printf("\n Invalid Choice "). &ch). Lecture Notes insertCQ(). Quit "). printf("\n 4. break. return ch. scanf("%d". displayCQ(). switch(ch) { case 1: case 2: case 3: case 4: default: } } getch(). 125 Dept.
6 shows the basic operations on a deque.5 shows the representation of a deque. • enqueue_rear: insert element at rear.4. Basic operations on deque There are two variations of deque. Figure 4. This data structure is a deque.5.9. which allows insertions at one end but allows deletions at both ends of the list. which allows deletions at one end but allows insertions at both ends of the list. • dequeue_front: delete an element at front. 11 22 enqueue_front(33) 33 11 22 enqueue_rear(44) 33 11 22 44 dequeue_front(33) 55 11 22 enqueue_front(55) 11 22 dequeue_rear(44) 11 22 44 Figure 4. Deque: In the preceding section we saw that a queue in which we insert items at one end and from which we remove items at the other end. The word deque is an acronym derived from doubleended queue. They are: • Input restricted deque (IRD) • Output restricted deque (ORD) An Input restricted deque is a deque. Figure 4. Representation of a deque. • enqueue_front: insert an element at front. Deletion 36 16 56 62 Insertion 19 Insertion Deletion front rear Figure 4. of Information Technology . An output restricted deque is a deque. A deque provides four operations. Lecture Notes 126 Dept. In this section we examine an extension of the queue. which provides a means to insert and remove items at both ends of the queue.6. • dequeue_rear: delete element at rear.
Transform the following infix expressions to reverse polish notation: a) A ↑ B * C – D + E / F / (G + H) b) ((A + B) * C – (D – E)) ↑ (F + G) c) A – B / (C * D ↑ E) d) (a + b ↑ c ↑ d) * (e + f / d)) f) 3 – 6 * 7 + 2 / 4 * 5 – 8 g) (A – B) / ((D + E) * F) h) ((A + B) / D) ↑ ((E – F) * G) 5. ↑. 9. A number: B. *. two elements with same priority are processed which they were added to the queue. 4. and programs with the same priority form a standard queue. Exercises 1. . A division sign: Lecture Notes 127 Dept. Draw the stack for the case where the 11th symbol is: A. A left parenthesis: C. of Information Technology . + c) P3 : 3. +. +. *. 5. Priority Queue: A priority queue is a collection of elements such that each element has been assigned a priority and such that the order in which elements are deleted and processed comes from the following rules: 1. 2. *. according to the order in A prototype of a priority queue is time sharing system: programs of high priority are processed first. Consider the usual algorithm to convert an infix expression to a postfix expression. An efficient implementation for the Priority Queue is to use heap. 2. +. 4.4. ↑.  6. 1. 6. +.10. b) P2: 3. Is it possible to have two designs for the same data structure that provide the same functionality but are implemented differently? 3. 2. Suppose that you have read 10 input characters during a conversion and that the stack now contains these symbols: bottom + ( * Now. 4. . 7. 2. 7. /. . An element of higher priority is processed before any element of lower priority. which in turn can be used for sorting purpose called heap sort. 2. . A minus sign: E. 3. What is the difference between the logical representation of a data structure and the physical representation? 4. What is a linear data structure? Give two examples of linear data structures. 5. suppose that you read and process the 11th symbol of the input. 1. 6. A right parenthesis: D. Evaluate the following postfix expressions: a) P1: 5. 2.
Write a “C” function for your algorithm.E)) ↑ (F + G) e) A – B / (C * D ↑ E) 10. “pop” operations on the stack and “add”. Write a “C” function to copy one stack to another assuming a) The stack is implemented using array. Represent a deque using an array to store the elements of the list and write the “C” functions for additions and deletions. of Information Technology . 17. Lecture Notes 128 Dept. 12. How can one convert a postfix expression to its prefix equivalent and viceversa? 13. A doubleended queue (deque) is a linear list where additions and deletions can be performed at either end. In a circular queue represented by an array. Write functions for “add” and “delete” operations on the ith queue 18. Write an algorithm to construct a fully parenthesized infix expression from its postfix equivalent. Write a program using stack for parenthesis matching. Evaluate the following prefix expressions: a) + * 2 + / 14 2 5 1 b) . Convert the following infix expressions to prefix notation: a) ((A + 2) * (B + 4)) 1 b) Z – ((((X + 1) * 2) – 5) / Y) c) ((C * 2) + 1) / (A + B) d) ((A + B) * C – (D .7. 15.13 2 4 9. Write functions for “push”. “rear” and MAXQUEUESIZE? Write a “C” function to delete the Kth element from the “front” of a circular queue.* 6 3 – 4 1 c) + + 2 6 + . Write a “C” function to test whether a string of opening and closing parenthesis is well formed or not. Represent a stack and queue in a single onedimensional array. how can one specify the number of elements in the queue in terms of “front”. 8. Can a queue be represented by a circular linked list with only one pointer pointing to the tail of the queue? Write “C” functions for the “add” and “delete” operations on such a queue 16. b) The stack is implemented using linked list. Explain what modifications would be needed to make the parenthesis matching algorithm check expressions with different kinds of parentheses such as (). “delete” functions on the queue. 11. [] and {}'s. Represent N queues in a single onedimensional array. 14.
none of the above 129 Dept.B / (C * D) A. Linked List D. A B + C D * .* E / [ D ] 7. In the middle D. all the above Stack is referred as: A./ C.* + X 1 2 5 Y C. / + * C 2 1 + A B D. Stack C. 2 D. none of the above [ B ] 11. none of the above [ C ] 10. . A. Which among the following is a Dynamic data structure: A. A B + 1 2 C * + / C. / . front and rear B. Queue D. A stack is a data structure in which all insertions and deletions of entries are made at: A. Transform the following infix expression to postfix form: A . Transform the following infix expression to postfix form: (A + B) * (C – D) / E A. First in first out list [ B ] Lecture Notes C.Multiple Choice Questions 1. A queue is a data structure in which all insertions and deletions are made respectively at: A. Transform the following infix expression to prefix form: Z – ((((X + 1) * 2) – 5) / Y) A. Which among the following is a linear data structure: A. / * . both A and B D.+ 4 3 5 / + 2 4 3 [ A ] 3. both A and B B. 4 B./ * A B C D [ B ] 8. Stack B. Evaluate the following postfix expression: 1 4 18 6 / 3 + + 5 / + A. A B + C D . 3 B. Queue is also known as: A.+ D. Evaluate the following prefix expression: * . Double Linked List C. none of the above [ D ] 12. A B * C + D / C. of Information Technology . rear and rear [ A ] 6. / * + 1 2 C A B + B. A B C D * / D.D C * B A B. First in first out list D. A B * C D . One end C./ D. Queue B. Last in first out list C. none of the above 9. / . Last in first out list B. Both the ends B. 8 C. Y 5 2 1 X + * . A B C * C D / . At any position [ A ] 5./ E B.+ X 1 2 5 Y B. front and front D. none of the above [ A ] [ A ] 4. 1 D. Transform the following infix expression to prefix form: ((C * 2) + 1) / (A + B) A. 8 C. all the above [ D ] 2. rear and front C.
[ B ] 21. Which of these pointers will change during an insertion into an EMPTY queue? A. A. Stacks use two ends of the structure. 'B'. None of these operations. The insert function would require linear time. Only rear_ptr changes.13. Both change. keeping track of a front pointer and a rear pointer. The is_empty function would require linear time. In the linked list implementation of the queue class. which operations require linear time for their worstcase behavior? A. Only front_ptr changes. Neither changes C. [ D ] Lecture Notes 130 Dept. ABCD C. To implement the queue with a linked list. After all other entries that are greater than the new entry. None of these. Only front_ptr changes. front C. Where does the push member function place the new entry in the array? A. D. [ B ] 17. but queues do not. D. with ten items in the queue stored at data[2] through data[11]. Queues require dynamic memory. data[12] [ D ] 16. D. The CAPACITY is 42. If the characters 'D'. [ ] 19. Stacks require dynamic memory. stacks use only one. C. data[1] C. in what order will they be removed? A. B. DCBA [ D ] 15. ABDC D. At the head B. push D. C. [ ] 20. B. Which of these pointers will change during an insertion into a NONEMPTY queue? A. Only rear_ptr changes. One difference between a queue and a stack is: A. 'C'. keeping track of a front pointer and a rear pointer. and then removed one at a time. What goes wrong if we try to keep all the items at the front of a partiallyfilled array (so that data[0] is always the front). B. Neither changes C. empty B. In the circular array version of the queue class (with a fixedsized array). In the linkedlist version of the queue class. Consider the implementation of the queue using a circular array. push D. Both change. D. The constructor would require linear time. of Information Technology . where does the push member function place the new entry on the linked list? A. queues use only one. empty B. To implement the queue with a linked list. 'A' are placed in a queue (in that order). B. Suppose we have a circular array implementation of the queue class. After all other entries that are smaller than the new entry. but stacks do not. [ A ] 18. which operations require linear time for their worstcase behavior? A. The get_front function would require linear time. data[11] B. front C. At the tail C. DCAB B. D. data[2] D. Queues use two ends of the structure. [ C ] 14.
+ + * + 2 3 4 * * 5 + 6 7 8 9 C. Something between 5 and 15 C. B. D. What is the maximum number of symbols that will appear on the stack AT ONE TIME during the conversion of this expression? A. and so on. [ D ] 28. Suppose that we are using the usual stack algorithm to convert the expression from infix to postfix notation. Here is an infix expression: 4 + 3 * (6 * 3 . 4 [ D ] 29. Suppose top is called on a priority queue that has exactly two entries with equal priority. The operation for adding an entry to a stack is traditionally called: A. add C. C. then the value obtained is same as the value of which of the following prefix expressions? A. The entries must be stored in a linked list. Stack entries may be compared with the '<' operation. D. is_empty C.12). * + + + 2 3 4 * * 5 + 6 7 8 9 B. Which of the following applications may use a stack? A. If the expression ((2 + 3) * 4 + 5 * (6 + 7) * 8) + 9 is evaluated with * having precedence over +. delete C. All of the above. B. 40 B. C. What is the meaning of this statement? A. 25 D. The one which was inserted most recently. There is a first entry. pop D. The one which was inserted first. C. B. The operation for removing an entry from a stack is traditionally called: A. append D. a second entry. + * + + 2 3 4 + + 5 * 6 7 8 9 [ A ] 31. This can never happen (violates the precondition) [ B ] 23. Something between 5 and 5 D. insert B. Something between 15 and 100 B. peek D. of Information Technology . push [ D ] 25. The implementation gets to choose either one. Two or more of the above answers [ C ] [ A ] 26. Something between 15 and 100 [ A ] 30. A parentheses balancing program. 2 D. Evaluate the following prefix expression: + * 2 + / 14 2 5 1 A. pop B. [ D ] 24. Entries in a stack are "ordered". 27. 15 [ B ] Lecture Notes 131 Dept. A collection of stacks can be sorted. What is the value of the postfix expression 6 3 2 4 + .22. Keeping track of local variables at run time. + * + + 2 3 4 * * 5 + 6 7 8 9 D.* A. 3 B. 50 C. Syntax analyzer for a compiler. Something between 5 and 15 E. How is the return value of top selected? A. push B. D. 1 C. remove Which of the following stack operations could result in stack underflow? A.
none of the above [ C ] 36. is less than its size: A. Cannot be expected B.32 Parenthesis are never needed prefix or postfix expression: A. Simple Queue C. Prefix expression C. of Information Technology . None of the above [ A ] 35. Queue [ D Lecture Notes 132 ] Dept. True C. even though the current number of elements in it. circular queue D. Stack C. linked list B. Stack B. both A and B D. Circular Queue D. False D. Fully parenthesized infix expression B. Cannot be expected B. False D. Conversion of infix arithmetic expression to postfix expression uses: A. True C. None of the above [ B ] 34 Which among the following data structure may give overflow error. Which among the following types of expressions does not require precedence rules for evaluation: A. None of the above [ A ] 33 A postfix expression is merely the reverse of the prefix expression: A.
A data structure is said to be non linear if its elements form a hierarchical classification where.1. Trees are recursive structures. Each child node is itself the root of a subtree. The links leaving a node (any number of links are allowed) point to child nodes. Ordered trees are by far the commonest form of tree data structure. 5. known as the root.e. Trees and Graphs are widely used nonlinear data structures.1 shows a tree and a nontree. Tree and graph structures represents hierarchial relationship between individual data elements. which have no children. a a b d c e b f c d A Tree e Not a Tree Figure 5.1. Previous linear data structures that we have studied like an array. A tree in which such distinctions are made is called an ordered tree. is at the top of the hierarchy.1. In a graph. data items appear at various levels. we will explain special type of trees known as binary trees. and data structures built on them are called ordered tree data structures. The node where the link originates is called the parent node. The root node has no parent. Graphs are nothing but trees with certain restrictions removed. which are easy to maintain in the computer. The figure 5.1 A Tree and a not a tree In a tree data structure. of Information Technology . TREES: A tree is hierarchical collection of nodes. there is no restrictions on the number of links that can enter or leave a node. and cycles may be present in the graph. Trees represent a special case of more general structures known as graphs. there is no distinction between the various children of a node i.Chapter 5 Binary Trees A data structure is said to be linear if its elements form a sequence or a linear list. queues and linked lists organize data in linear order. In this chapter in particular. One of the nodes. none is the "first child" or "last child". stacks. At the bottom of the tree are leaf nodes. Each node can have at most one link coming into it.. Lecture Notes 133 Dept.
. . Tree Terminology: Leaf node A node with no children is called a leaf (or external node). nk. Lecture Notes 134 Dept. F and G are the siblings of the parent node C and H and I are the siblings of the parent node D. D. of Information Technology ..2. A binary tree is shown in figure 5.1. . For the tree shown in figure 5. with all of its descendants is a subtree.2. For the tree shown in figure 5.. B.1. each node can have at most two children.2. A binary tree is either empty or consists of a node called the root together with two binary trees called the left subtree and the right subtree.5. Path A sequence of nodes n1. . tree nodes can have any number of children. BINARY TREE: In general. The length of a path is 1 less than the number of nodes on the path. Because of this characteristic.2. In a binary tree. I.1.1. Binary Tree Binary trees are easy to implement because they have a small. 2. Thus there is a path of length zero from a node to itself. the path between A and I is A.1.2. .. fixed number of child links. k . binary trees are the most common types of trees and form the basis of many important data structures. such that ni is the parent of ni + 1 for i = 1. Ancestor and Descendent If there is a path from node A to node B. Subtree Any node of a tree. n2. A node which is not a leaf is called an internal node. A tree with no nodes is called as a null tree. Siblings The children of the same parent are called siblings. then A is called an ancestor of B and B is called a descendent of A. A left child B H F E D left subtree C right child right subtree G I Figure 5.
1 has a depth of 1.2. The root of the tree has level O. left to right. of Information Technology . If h = height of a binary tree. level by level. Level 0 1 4 8 Level 1 3 2 5 6 Level 2 7 Level 3 9 Figure 5.2.2.2. Maximum number of leaves = 2h b. and the level of any other node in the tree is one more than the level of its parent.1 is 3.2.1. see Figure 5. Depth The depth of a node is the number of nodes along the path from the root to that node. 4. 3. Lecture Notes 135 Dept.1 node F is at level 2 and node H is at level 3. Level by level numbering of binary tree Properties of binary trees: Some of the important properties of a binary tree are as follows: 1. The height of the tree of Figure 5. it contains at most 2m nodes at level l + 1. and a right child is assigned one more than twice the number assigned its parent. in the binary tree of Figure 5. Since a binary tree can contain at most one node at level 0 (the root). If a binary tree contains m nodes at level l. Height The maximum level in a tree determines its height. The total number of edges in a full binary tree with n node is n . The height of a node in a tree is the length of a longest path from the node to a leaf. The maximum number of nodes at any level is 2n. The nodes of a complete binary tree can be numbered so that the root is assigned the number 1. The term depth is also used to denote height of the tree.2. it can contain at most 2l node at level l. node ‘C’ in figure 5.Level The level of the node refers to its distance from the root.1 2. For example. then a. a left child is assigned twice the number assigned its parent. Maximum number of nodes = 2h + 1 . For example. Assigning level numbers and Numbering of nodes for a binary tree: The nodes of a binary tree can be numbered in a natural way.2. For instance.
All non leaf nodes of a full binary tree have two children. l =0 For example. Examples of binary trees Complete Binary tree: A binary tree with n nodes is said to be complete if it contains all the first n nodes of the above numbering scheme. and the leaf nodes have no children. A complete binary tree of height h looks like a full binary tree down to level h1. the tree is termed as strictly binary tree. Full Binary tree: A full binary tree of height h has all its leaves at level h. A full binary tree with height h has 2h + 1 . 2h . A full binary tree of height h contains 2h leaves and. 1 1 Strict Binary Tree (a) 2 6 12 7 4 13 8 9 7 Strictly Complete binary tree (b) 1 2 2 3 5 6 5 9 8 1 4 3 2 3 6 4 7 8 10 Complete binary tree 3 5 9 10 6 11 12 7 13 Full binary tree (c) 14 15 (d) Figure 5. Alternatively. h Thus by induction. Figure 5. and the level h is filled from left to right.4 shows examples of complete and incomplete binary trees.2.2.3.3(a) is strictly binary.2.1 nonleaf nodes.2. Lecture Notes 136 Dept. Thus the tree of figure 5. A strictly binary tree with n leaves always contains 2n .3(d) illustrates the full binary tree containing 15 nodes and of height 3. Figure 5. total number of nodes ( tn) = ∑ 2 l = 2 h + 1 − 1 .1 nodes. A full binary tree of height h is a strictly binary tree all of whose leaves are at level h.Strictly Binary tree: If every nonleaf node in a binary tree has nonempty left and right subtrees. of Information Technology .1 nodes. a full binary tree of height 3 contains 23+1 – 1 = 15 nodes.
Figure 5. this method wastes no space. especially suited for complete and full binary trees. b. and if the tree is a complete binary tree. while its parent (if any) is found at index floor((i1)/2) (assuming the root of the tree stored in the array at an index zero). 2. External nodes are denoted by squares. Examples of complete and incomplete binary trees Internal and external nodes: We define two terms: Internal nodes and external nodes. Pointerbased.4. Arrays.3(c) is a complete binary tree having 5 leaves and 10 nodes. if a node has an index i. Lecture Notes 137 Dept. Internal and external nodes Data Structures for Binary Trees: 1. and pretend that all null child links point to such a node. 4. It is some times convenient to have another types of nodes.2. c a d b 1 2 4 Internal Nodes: a. We draw internal nodes using circles.A complete binary tree with n leaves that is not strictly binary has 2n nodes.6.2.6 shows a sample tree illustrating both internal and external nodes. d External Nodes: 1.2. Arraybased Implementation: Binary trees can also be stored in arrays. 5 5 3 Figure 5. 2. An external node doesn’t exist. c. of Information Technology . The square node version is sometimes called an extended binary tree. the tree of Figure 5. with letters as labels. 1 1 3 2 4 5 1 2 6 3 4 Complete Binary Tree but not strict (a) 5 2 7 4 Not C omplete and not strict (b) Not C omplete and not strict (c) Figure 5. its children are found at indices 2i+1 and 2i+2. For example. 3. A binary tree with n internal nodes has n+1 external nodes. but serves as a conceptual place holder for nodes to be inserted.2. An internal node is a tree node having at least one–key and possibly some children. called an external node. In this compact arrangement.
The representation suffers from insertion and deletion of node from the middle of the tree. • Memory spaces are wasted for storing NULL pointers for the nodes. it is difficult to determine its parent node. which have no subtrees.This method benefits from more compact storage and better locality of reference. node: LeftC hild Empty Tree: typedef struct binarytree node.2. Structure definition. particularly during a preorder traversal. node representation empty binary tree is shown in figure 5.7. node representation and empty tree Lecture Notes 138 Dept. }. struct binarytree *RightChild.6 and the linked representation of binary tree using this node structure is given in figure 5. the left child field denoted as LeftChild. it requires contiguous memory. but it is wasteful for many other binary trees. The advantage of using linked representation of binary tree is that: • Insertion and deletion involve no data movement and no movement of nodes except the rearrangement of pointers. The disadvantages of linked representation of binary tree includes: • Given a node structure. struct binarytree { struct binarytree *LeftChild.2. 0 1 2 3 4 5 6 Linked Representation (Pointer based): Array representation is good for complete binary tree. as it requires the moment of potentially many nodes to reflect the change in level number of this node. data field denoted as data and the right child field denoted as RightChild. Figure 5. The structure definition. of Information Technology . data RightChild root NULL node *root = NULL. int data. To overcome this difficulty we represent the binary tree in linked representation. However. expensive to grow and wastes space proportional to 2h .2. If the tree itself is empty the root pointer will store a NULL value.n for a tree of height h with n nodes. In linked representation each node in a binary has three fields.6. If any subtree is empty then the corresponding pointer’s LeftChild and RightChild will store a NULL value.
Inorder 3. There are four common ways to traverse a binary tree: 1. using inorder. of Information Technology . Binary Tree Traversal Techniques: A tree traversal is a method of visiting every node in the tree. Visit the left subtree.3. Visit the right subtree. the root of each subtree is visited after its left subtree has been traversed but before the traversal of its right subtree begins. Visit the root. using inorder. you may wish to print the contents of the nodes. the left subtree of a node is traversed before the right subtree.7. 3. 5. Recursive Traversal Algorithms: Inorder Traversal: In the case of inorder traversal. we mean that some type of operation is performed.1. The algorithm for inorder traversal is as follows: void inorder(node *root) { if(root != NULL) { inorder(root>lchild). For example. Postorder 4. The difference among them comes from the difference in the time at which a root node is visited.A root B D C E F A G B H C I D X H X X I X E X X F X X G X X Figure 5. Preorder 2. 2.3. The steps for traversing a binary tree in inorder traversal are: 1. Lecture Notes 139 Dept.2. Level order In the first three traversal methods. Linked representation for the binary tree 5. By visit.
preorder (root > lchild). each root node is visited before its left and right subtrees are traversed. } } Postorder Traversal: In a postorder traversal. using postorder 3. using postorder. Visit the root. The steps for traversing a binary tree in preorder traversal are: 1. the nodes are visited level by level starting from the root. Visit the right subtree. 2. Preorder search is also called backtracking. Visit the right subtree.} print root > data. This is nothing but a breadth first search technique. The algorithm for postorder traversal is as follows: void postorder(node *root) { if( root != NULL ) { postorder (root > lchild). } } Level order Traversal: In a level order traversal. Visit the left subtree. The algorithm for preorder traversal is as follows: void preorder(node *root) { if( root != NULL ) { print root > data. } Preorder Traversal: In a preorder traversal. inorder(root>rchild). each root is visited after its left and right subtrees have been traversed. preorder (root > rchild). Lecture Notes 140 Dept. So. using preorder. postorder (root > rchild). and going from left to right. using preorder. The level order traversal requires a queue data structure. Visit the left subtree. 2. print (root > data). The steps for traversing a binary tree in postorder traversal are: 1. Visit the root. 3. of Information Technology . it is not possible to develop a recursive procedure to traverse the binary tree in level order.
R. T. G . I F H G I Bi n a ry T r e e Pr e. S. j < ctr. D. C . D. C . G . H. E . j++) { if(tree[j] != NULL) print tree[j] > data. G . post. R. W . S. G . I n or d er a n d l ev e l or d er T r av er s i n g 141 Dept. B . } } Example 1: Traverse the following binary tree in pre. P o st . I. H. W . P • Ino r d e r t r a v e rs a l y ie lds: B. G . A . T. H . W Y T Z W Bi n a ry T r e e • Pr e. Y. F . Z. S. E . H . Z • L e v e l o r d e r t r a v e rs a l y ie lds: P. P F B S H R G Lecture Notes P r eo r d e r t r a v e rs a l y ie lds: P. for(j = 0. R. I • L e v e l o r d e r t r a v e rs a l y ie lds: A . Z. F . G . P o st . Y. I n or d er a n d l ev e l or d er T r av er s i n g Example 2: Traverse the following binary tree in pre. of Information Technology . C .The algorithm for level order traversal is as follows: void levelorder() { int j. F . H. A B C E D • P r eo r d e r t r a v e rs a l y ie lds: A . A • Ino r d e r t r a v e rs a l y ie lds: D. P. H . H. Y. E . B . E . S. post. F . F . H . B . B. C . I • Po sto r d e r t r a v e rs a l y ie lds: D. F . G . W . B. G . R. Y. T. B . F . Z • Po sto r d e r t r a v e rs a l y ie lds: B. inorder and level order. T. F . inorder and level order.
7 . 5 . I n or d er a n d l ev e l or d er T r av er s i n g Building Binary Tree from Traversal Pairs: Sometimes it is required to construct a binary tree if its traversals are known. C • L e v e l o r d e r t r a v e rs a l y ie lds: A . 5 . Same technique can be applied repeatedly to form subtrees. L . 4 • Po sto r d e r t r a v a rs a l y ie lds: 2. L . E . 6 . K . L .3. 5 . P r eo r d e r t r a v e rs a l y ie lds: A . inorder and level order. K .Example 3: Traverse the following binary tree in pre. C . I n or d er a n d l ev e l or d er T r av er s i n g Example 4: Traverse the following binary tree in pre. From a single traversal it is not possible to construct unique binary tree. L . H . If the postorder traversal is given then the last node is the root node. 2 . E • Po sto r d e r t r a v a rs a l y ie lds: K . D. B . E . 2 . then the first node is the root node. 4 9 11 5 • 4 Bi n a ry T r e e Pr e. 11 . 9 . Lecture Notes 142 Dept. B . 4 . B . M . 7 . P o st . P o st . M . 2 • Ino r d e r t r a v a rs a l y ie lds: 2. 11 . G . 7 . 5 . H . G . 11 . post. B . 9 • L e v e l o r d e r t r a v e rs a l y ie lds: 2. D. D. all the nodes in the left subtrees and right subtrees of the root node can be identified using inorder. 5 . inorder and level order. 7 . 4 . post. 11 . G . 5 . However any of the two traversals are given then the corresponding tree can be drawn uniquely: • • • Inorder and preorder Inorder and postorder Inorder and level order The basic principle for formulation is as follows: If the preorder traversal is given. A • Ino r d e r t r a v a rs a l y ie lds: K . 9 . 6 . of Information Technology . G . 5 . D.2. H . M . 5 . E . Once the root node is identified. 2 7 2 5 6 P r eo r d e r t r a v e rs a l y ie lds: 2. A . M E D G • Pr e. A B C H K L M Bi n a ry T r e e 5. 6 . C . 9 . 6 . 2 . H . C .
alternatively. left and right sub trees for D G B: From the preorder sequence B D G. two traversal are essential out of which one should be inorder traversal and another preorder or postorder. given preorder and postorder traversals. the root of tree is: B From the inorder sequence D G B. left and right sub trees for D G: From the preorder sequence D G. of Information Technology . Example 1: Construct a binary tree from a given preorder and inorder sequence: Preorder: A B D G C E H I F Inorder: D G B A H E I C F Solution: From Preorder sequence A B D G C E H I F. Lecture Notes 143 Dept. for the purpose mentioned. the root is: A From Inorder sequence D G B A H E I C F. we can find that there is no left node to D and G is at the right of D. we get the left and right sub trees: Left sub tree is: D G B Right sub tree is: H E I C F The Binary tree upto this point looks like: A D G B H E I C F To find the root. binary tree cannot be obtained uniquely. we can find that D and G are to the left of B. the root of the tree is: D From the inorder sequence D G.It can be noted that. The Binary tree upto this point looks like: A B H E I C F D G To find the root.
The Binary tree upto this point looks like: A B H E I C F D G To find the root. left and right sub trees for H E I: From the preorder sequence E H I. we can find that H E I are at the left of C and F is at the right of C. of Information Technology . The Binary tree upto this point looks like: A B C E D G H F I Example 2: Construct a binary tree from a given postorder and inorder sequence: Inorder: D G B A H E I C F Postorder: G D B H I E F C A Lecture Notes 144 Dept. we can find that H is at the left of E and I is at the right of E. the root of the tree is: E From the inorder sequence H E I. The Binary tree upto this point looks like: A B C D F H E I G To find the root. the root of the left sub tree is: C From the inorder sequence H E I C F. left and right sub trees for H E I C F: From the preorder sequence C E H I F.
the root of tree is: B From the inorder sequence D G B. we can find that D G are to the left of B and there is no right subtree for B. the root of the tree is: D From the inorder sequence D G. left and right sub trees for H E I C F: From the postorder sequence H I E F C. The Binary tree upto this point looks like: A B H E I C F D G To find the root. the root of the left sub tree is: C From the inorder sequence H E I C F. of Information Technology . we get the left and right sub trees: Left sub tree is: D G B Right sub tree is: H E I C F The Binary tree upto this point looks like: A D G B H E I C F To find the root. we can find that H E I are to the left of C and F is the right subtree for C. Lecture Notes 145 Dept. the root is: A From Inorder sequence D G B A H E I C F. The Binary tree upto this point looks like: A B H E I C F D G To find the root. we can find that is no left subtree for D and G is to the right of D. left and right sub trees for D G: From the postorder sequence G D. left and right sub trees for D G B: From the postorder sequence G D B.Solution: From Postorder sequence G D B H I E F C A.
left and right sub trees for H E I: From the postorder sequence H I E. the root of the tree is: E From the inorder sequence H E I. of Information Technology . we can find that H is left subtree for E and I is to the right of E. we get the left and right sub trees: Left sub tree is: n1 n2 n3 n4 n5 Right sub tree is: n7 n8 n9 The Binary tree upto this point looks like: n6 n1 n2 n3 n4 n5 Lecture Notes n7 n8 n9 146 Dept. The Binary tree upto this point looks like: A B C D F E G H I Example 3: Construct a binary tree from a given preorder and inorder sequence: Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9 Preorder: n6 n2 n1 n4 n3 n5 n9 n7 n8 Solution: From Preorder sequence n6 n2 n1 n4 n3 n5 n9 n7 n8.The Binary tree upto this point looks like: A C B D F H E I G To find the root. the root is: n6 From Inorder sequence n1 n2 n3 n4 n5 n6 n7 n8 n9.
we can find that n3 is to the left of n4 and n5 is at the right of n4. left and right sub trees for n7 n8 n9: From the preorder sequence n9 n7 n8. the root of the left sub tree is: n9 From the inorder sequence n7 n8 n9. The Binary tree upto this point looks like: n6 n9 n2 n4 n1 n3 n7 n8 n5 To find the root. we can find that n1 is to the left of n2 and n3 n4 n5 are to the right of n2. left and right sub trees for n3 n4 n5: From the preorder sequence n4 n3 n5. the root of the tree is: n7 Lecture Notes 147 Dept. The Binary tree upto this point looks like: n6 n2 n1 n7 n8 n9 n3 n4 n5 To find the root. left and right sub trees for n1 n2 n3 n4 n5: From the preorder sequence n2 n1 n4 n3 n5. left and right sub trees for n7 n8: From the preorder sequence n7 n8. the root of the tree is: n4 From the inorder sequence n3 n4 n5. The Binary tree upto this point looks like: n6 n2 n1 n7 n8 n9 n4 n3 n5 To find the root. of Information Technology .To find the root. the root of tree is: n2 From the inorder sequence n1 n2 n3 n4 n5. we can find that n7 and n8 are at the left of n9 and no right subtree of n9.
we get the left and right sub trees: Left sub tree is: n1 n2 n3 n4 n5 Right sub tree is: n7 n8 n9 The Binary tree upto this point looks like: n6 n1 n2 n3 n4 n5 n7 n8 n9 To find the root.From the inorder sequence n7 n8. we can find that is no left subtree for n7 and n8 is at the right of n7. the root is: n6 From Inorder sequence n1 n2 n3 n4 n5 n6 n7 n8 n9. the root of tree is: n2 From the inorder sequence n1 n2 n3 n4 n5. The Binary tree upto this point looks like: n6 n2 n1 Lecture Notes n7 n8 n9 n3 n4 n5 148 Dept. we can find that n1 is to the left of n2 and n3 n4 n5 are to the right of n2. The Binary tree upto this point looks like: n6 n9 n2 n4 n1 n3 n7 n5 n8 Example 4: Construct a binary tree from a given postorder and inorder sequence: Inorder: n1 n2 n3 n4 n5 n6 n7 n8 n9 Postorder: n1 n3 n5 n4 n2 n8 n7 n9 n6 Solution: From Postorder sequence n1 n3 n5 n4 n2 n8 n7 n9 n6. of Information Technology . left and right sub trees for n1 n2 n3 n4 n5: From the postorder sequence n1 n3 n5 n4 n2.
To find the root. the root of the left sub tree is: n9 From the inorder sequence n7 n8 n9. left and right sub trees for n7 n8 and n9: From the postorder sequence n8 n7 n9. we can find that n3 is to the left of n4 and n5 is to the right of n4. we can find that there is no left subtree for n7 and n8 is to the right of n7. The Binary tree upto this point looks like: n6 n2 n1 n7 n4 n3 Lecture Notes n9 n5 n8 149 Dept. the root of the tree is: n7 From the inorder sequence n7 n8. left and right sub trees for n7 and n8: From the postorder sequence n8 n7. The Binary tree upto this point looks like: n6 n2 n1 n7 n8 n9 n4 n3 n5 To find the root. the root of the tree is: n4 From the inorder sequence n3 n4 n5. left and right sub trees for n3 n4 n5: From the postorder sequence n3 n5 n4. we can find that n7 and n8 are to the left of n9 and no right subtree for n9. of Information Technology . The Binary tree upto this point looks like: n6 n2 n1 n9 n7 n8 n4 n3 n5 To find the root.
scanf("%d".5. do { if( j > 0 ) { tree[ i * 2 + 1 ] = getnode(). 7. 6. temp = (node*) malloc(sizeof(node)). typedef struct tree node. Binary Tree Creation and Traversal Using Arrays: This program performs the following operations: 1. 4. printf("\n How many nodes you want: "). j. j = ctr. } Lecture Notes 150 /* left child */ /* right child */ Dept.h> struct tree { struct tree* lchild. scanf("%s". char data[10]. node* getnode() { node *temp . } if( j > 0 ) { tree[i * 2 + 2] = getnode().h> # include <stdlib. j. tree[i]>rchild = tree[i * 2 + 2]. 3. 2.temp>data).3. } i++. } void create_fbinarytree() { int j. node *tree[100]. tree[0] = getnode(). 5. return temp. i=0. }. j. struct tree* rchild.3. temp>lchild = NULL. int ctr.&ctr). temp>rchild = NULL. of Information Technology . printf("\n Enter Data: "). } while( j > 0). tree[i]>lchild = tree[i * 2 + 1]. Creates a complete Binary Tree Inorder traversal Preorder traversal Postorder traversal Level order traversal Prints leaf nodes Finds height of the tree created # include <stdio.
inorder(root>rchild). print_leaf(root>rchild). preorder(root>lchild). printf("%3s".root>data). of Information Technology . } } void print_leaf(node *root) { if(root != NULL) { if(root>lchild == NULL && root>rchild == NULL) printf("%3s ". } } void postorder(node *root) { if( root != NULL ) { postorder(root>lchild). printf("%3s". for(j = 0. postorder(root>rchild). } Lecture Notes 151 Dept. j < ctr.root>data). } } void levelorder() { int j.void inorder(node *root) { if( root != NULL ) { inorder(root>lchild). j++) { if(tree[j] != NULL) printf("%3s". preorder(root>rchild).root>data). } } void preorder(node *root) { if( root != NULL ) { printf("%3s".root>data).tree[j]>data). print_leaf(root>lchild). } } int height(node *root) { if(root == NULL) { return 0.
create_fbinarytree(). printf("\n Postorder Traversal: ").temp>data). 6. node* getnode() { node *temp . }. preorder(tree[0]). inorder(tree[0]). return temp. printf("\n Inorder Traversal: ").4. 2. height(tree[0])). 5. of Information Technology . postorder(tree[0]). scanf("%s".h> struct tree { struct tree* lchild. Binary Tree Creation and Traversal Using Pointers: This program performs the following operations: 1. Creates a complete Binary Tree Inorder traversal Preorder traversal Postorder traversal Level order traversal Prints leaf nodes Finds height of the tree created Deletes last node Finds height of the tree created # include <stdio. typedef struct tree node. levelorder(). height(root>rchild))). printf("\n Leaf Nodes: "). 7. 9.if(root>lchild == NULL && root>rchild == NULL) return 0. printf("\n Height of Tree: %d ". } void main() { int i. char data[10]. fflush(stdin). printf("\n Preorder Traversal: "). temp>rchild = NULL. temp = (node*) malloc(sizeof(node)).h> # include <stdlib. } Lecture Notes 152 Dept. print_leaf(tree[0]). int node_ctr. struct tree* rchild. temp>lchild = NULL. } 5. else return (1 + max(height(root>lchild). printf("\n Enter Data: "). node *Q[50].3. printf("\n Level Order Traversal: "). 4. 3. 8.
create_binarytree(root>lchild). if( root != NULL ) { printf("\n Node %s has Left SubTree(Y/N)". create_binarytree(root>lchild). if(root == NULL) printf("\n Empty TREE "). Q[parent] = root. make_Queue(root>lchild.&option). node_ctr++. Q[index] = NULL.&option). if( 2* parent + 1 == index ) Q[parent]>lchild = NULL.void create_binarytree(node *root) { char option. of Information Technology . index = node_ctr1. int parent) { int index = 0. create_binarytree(root>rchild).root>data). node_ctr = 1. if( option=='Y'  option == 'y') { root>rchild = getnode(). scanf("%c". parent = (index1) /2. make_Queue(root>rchild. } } void make_Queue(node *root. } else { root>rchild = NULL. fflush(stdin).parent*2+2).0). } } printf("\n Node %s has Right SubTree(Y/N) ". create_binarytree(root>rchild). } else { root>lchild = NULL. else { node_ctr = 0. if( option=='Y'  option == 'y') { root>lchild = getnode(). node_ctr++. } } delete_node(node *root.int parent) { if(root != NULL) { node_ctr++. fflush(stdin). Lecture Notes 153 Dept. make_Queue(root. scanf("%c".parent*2+1).root>data).
root>data). printf("%3s". printf("\n")..i<line. } void print_tree(node *root. for(i=0. print_leaf(root>lchild).line+1). preorder(root>rchild). } } void preorder(node *root) { if( root != NULL ) { printf("%3s". } } int height(node *root) { if(root == NULL) return 1. } } void print_leaf(node *root) { if(root != NULL) { if(root>lchild == NULL && root>rchild == NULL) printf("%3s ". root>data).root>data). } printf("\n Node Deleted . postorder(root>rchild). print_leaf(root>rchild). if(root != NULL) { print_tree(root>rchild. height(root>rchild))). inorder(root>rchild). else return (1 + max(height(root>lchild). int line) { int i.else } Q[parent]>rchild = NULL."). } } void postorder(node *root) { if( root != NULL ) { postorder(root>lchild). void inorder(node *root) { if(root != NULL) { inorder(root>lchild).i++) Lecture Notes 154 Dept. of Information Technology .root>data). printf("%3s". preorder(root>lchild).
Level Order Traversal"). printf("\n 6. print_tree(root>lchild. create_binarytree(root). return ch. printf("\n 10. Print Binary Tree "). Inorder Traversal "). printf("\n 4. i++) { if( Q[i] != NULL ) printf("%5s". clrscr(). i < ctr . Leaf Node "). printf("\n 9.int ctr) { int i. printf("%s". case 2 : printf("\n Inorder Traversal: "). break. printf("\n 8. case 3 : printf("\n Preorder Traversal: "). Preorder Traversal "). preorder(root). printf("\n 1. Lecture Notes 155 Dept. scanf("%d". printf("\n 3. for( i = 0. Create Binary Tree "). of Information Technology . } break. } void main() { int i. printf("\n 5. inorder(root).ch. switch( ch) { case 1 : if( root == NULL ) { root = getnode().line+1). void level_order(node *Q[]. do { ch = menu(). Print Height of Tree "). printf("\n Enter Your choice: "). Postorder Traversal "). printf("\n 2. } } int menu() { int ch.} } printf(" "). Delete a node "). root>data)..Q[i]>data). &ch). printf("\n 7. Quit "). node *root = NULL."). } else { printf("\n Tree is already Created . break.
}while(1). level_order(Q.. break."). Non Recursive Traversal Algorithms: At first glance. break. } 5. case 5: printf("\n Level Order Traversal . make_Queue(root. But the flat versions are not necessarily better. If a vertex with right son exists. Inorder Traversal: Initially push zero onto stack and then set root as vertex. which may negate the savings we gain from storing only node pointers. Pop and process the nodes on stack if zero is popped then exit. pushing each vertex onto the stack and stop when there is no left son of vertex. case 7 : printf("\n Height of Tree: %d ". case 9 : delete_node(root. height(root)). break. Then repeat the following steps until the stack is empty: 1.case 4 : printf("\n Postorder Traversal: "). break. print_tree(root. break. it appears that we would always want to use the flat traversal functions since they use less stack space. 0).0). case 6 : printf("\n Leaf Nodes: "). case 8 : printf("\n Print Tree \n"). Proceed down the left most path rooted at vertex. } getch(). case 10 : exit(0).node_ctr). break.5. then set right son of vertex as current vertex and return to step one. some overhead is associated with the use of an explicit stack. of Information Technology . postorder(root).3. Algorithm inorder() { stack[1] = 0 vertex = root top: while(vertex ≠ 0) { push the vertex into the stack vertex = leftson(vertex) Lecture Notes 156 Dept. 2. For instance. print_leaf(root).0). Use of the implicit function call stack may actually be faster due to special machine instructions that can be used.
The traversing ends after a vertex with no left child exists. 2. of Information Technology . Lecture Notes 157 Dept. if any and process each vertex. Then repeat the following steps until the stack is empty: 1. Pop the vertex from stack. if vertex ≠ 0 then return to step one otherwise exit. At each vertex of path push vertex on to stack and if vertex has a right son push –(right son of vertex) onto stack. Proceed down the left most path by pushing the right son of vertex onto stack. If a negative node is popped. Proceed down the left most path rooted at vertex. then ignore the sign and return to step one. while(vertex ≠ 0) { print vertex node if(rightson(vertex) ≠ 0) push the right son of vertex into the stack. If zero is popped then exit.} pop the element from the stack and make it as vertex while(vertex ≠ 0) { print the vertex node if(rightson(vertex) ≠ 0) { vertex = rightson(vertex) goto top } pop the element from the stack and made it as vertex } } Preorder Traversal: Initially push zero onto stack and then set root as vertex. if(leftson(vertex) ≠ 0) vertex = leftson(vertex) else pop the element from the stack and made it as vertex } } Postorder Traversal: Initially push zero onto stack and then set root as vertex. Algorithm preorder( ) { stack[1] = 0 vertex = root. 2. Pop and process the positive nodes (left nodes). Then repeat the following steps until the stack is empty: 1.
If a vertex with right son exists. A C B E D G K H L M Bi n a ry T r e e • P r eo r d e r t r a v e rs a l y ie lds: A . L . C .(vertex) goto top } } Example 1: Traverse the following binary tree in pre. G . E . of Information Technology . A . 2. M . Proceed down the left most path rooted at vertex. D. Then repeat the following steps until the stack is empty: 1. pushing each vertex onto the stack and stop when there is no left son of vertex. B . M . K . D. D. E . E • Po sto r d e r t r a v a rs a l y ie lds: K . then set right son of vertex as current vertex and return to step one. Lecture Notes 158 Dept. L . C Pr e. H . post and inorder using nonrecursive traversing algorithm. P o st a n d I n or d er T r av er s i n g Inorder Traversal: Initially push zero onto stack and then set root as vertex. H . Pop and process the nodes on stack if zero is popped then exit. B . B . L . C . G .Algorithm postorder( ) { stack[1] = 0 vertex = root top: while(vertex ≠ 0) { push vertex onto stack if(rightson(vertex) ≠ 0) push – (vertex) onto stack vertex = leftson(vertex) } pop from stack and make it as vertex while(vertex > 0) { print the vertex node pop from stack and make it as vertex } if(vertex < 0) { vertex = . G . M . H . A • Ino r d e r t r a v a rs a l y ie lds: K .
If zero is popped then exit. CURRENT VERTEX STACK A 0 PUSH 0 0 A –C B D –H G K PUSH the left most path of A with a ve for right sons H Lecture Notes PROCESSED NODES REMARKS 0 A –C B D –H KG POP all +ve nodes K and G 0 A –C B D KG Pop H 159 Dept. then ignore the sign and return to step one. of Information Technology . 2. Then repeat the following steps until the stack is empty: 1. If a negative node is popped. Proceed down the left most path rooted at vertex.CURRENT VERTEX STACK A 0 PUSH 0 0ABDGK PUSH the left most path of A PROCESSED NODES REMARKS K 0ABDG K POP K G 0ABD KG POP G since K has no right son D 0AB KGD POP D since G has no right son H 0AB KGD Make the right son of D as vertex 0ABHL KGD PUSH the leftmost path of H L 0ABH KGDL POP L H 0AB KGDLH POP H since L has no right son M 0AB KGDLH Make the right son of H as vertex 0ABM KGDLH PUSH the left most path of M M 0AB KGDLHM POP M B 0A KGDLHMB POP B since M has no right son A 0 KGDLHMBA Make the right son of A as vertex C 0CE KGDLHMBA PUSH the left most path of C E 0C KGDLHMBAE POP E C 0 KGDLHMBAEC Stop since stack is empty Postorder Traversal: Initially push zero onto stack and then set root as vertex. At each vertex of path push vertex on to stack and if vertex has a right son push –(right son of vertex) onto stack. Pop and process the positive nodes (left nodes).
Proceed down the left most path by pushing the right son of vertex onto stack. Then repeat the following steps until the stack is empty: 1. C and A 0 KGLMHDBECA Stop since stack is empty C Preorder Traversal: Initially push zero onto stack and then set root as vertex. 2. D and B 0A KGLMHDB Pop C 0ACE KGLMHDB PUSH the left most path of C with a ve for right sons 0 KGLMHDBECA POP all +ve nodes E. of Information Technology .0 A –C B D H –M L KG PUSH the left most path of H with a ve for right sons L 0 A –C B D H –M KGL POP all +ve nodes L M 0 A –C B D H KGL Pop M 0 A –C B D H M KGL PUSH the left most path of M with a ve for right sons 0 A –C KGLMHDB POP all +ve nodes M. CURRENT VERTEX STACK A 0 H M C PROCESSED NODES REMARKS PUSH 0 0CH ABDGK PUSH the right son of each vertex onto stack and process each vertex in the left most path 0C ABDGK POP H 0CM ABDGKHL PUSH the right son of each vertex onto stack and process each vertex in the left most path 0C ABDGKHL POP M 0C ABDGKHLM PUSH the right son of each vertex onto stack and process each vertex in the left most path. H. Pop the vertex from stack. if any and process each vertex. M has no left path 0 ABDGKHLM Pop C 0 ABDGKHLMCE PUSH the right son of each vertex onto stack and process each vertex in the left most path. C has no right son on the left most path 0 ABDGKHLMCE Stop since stack is empty Lecture Notes 160 Dept. if vertex ≠ 0 then return to step one otherwise exit. The traversing ends after a vertex with no left child exists.
11 . If a vertex with right son exists. 6 . pushing each vertex onto the stack and stop when there is no left son of vertex. 2 . 9 . 11 . 11 . P o st a n d I n or d er T r av er s i n g Inorder Traversal: Initially push zero onto stack and then set root as vertex. 2 7 2 P r eo r d e r t r a v e rs a l y ie lds: 2. 2 • Ino r d e r t r a v a rs a l y ie lds: 2. 9 5 6 5 • 9 11 4 Bi n a ry T r e e Pr e. 5 .Example 2: Traverse the following binary tree in pre. CURRENT VERTEX STACK 2 0 PROCESSED NODES REMARKS 0272 2 027 2 7 02 27 6 0265 27 5 026 275 6 02 2756 11 0 2 11 2756 11 02 2 7 5 6 11 2 0 2 7 5 6 11 2 5 05 2 7 5 6 11 2 5 0 2 7 5 6 11 2 5 9 094 2 7 5 6 11 2 5 4 09 2 7 5 6 11 2 5 4 9 0 2 7 5 6 11 2 5 4 9 Lecture Notes 161 Stop since stack is empty Dept. 2 . 6 . Pop and process the nodes on stack if zero is popped then exit. Proceed down the left most path rooted at vertex. 7 . 2. 5 . of Information Technology . 7 . then set right son of vertex as current vertex and return to step one. 4 . 5 . 4 • Po sto r d e r t r a v a rs a l y ie lds: 2. 4 . 9 . post and inorder using nonrecursive traversing algorithm. 7 . Then repeat the following steps until the stack is empty: 1. 6 . 5 . 5 . 5 .
At each vertex of path push vertex on to stack and if vertex has a right son push –(right son of vertex) onto stack. then ignore the sign and return to step one. 2. Proceed down the left most path rooted at vertex. Proceed down the left most path by pushing the right son of vertex onto stack.Postorder Traversal: Initially push zero onto stack and then set root as vertex. Pop the vertex from stack. If a negative node is popped. of Information Technology . CURRENT VERTEX STACK 2 0 PROCESSED NODES REMARKS 0 2 –5 7 –6 2 2 0 2 –5 7 –6 2 6 0 2 –5 7 2 0 2 –5 7 6 –11 5 2 5 0 2 –5 7 6 –11 25 11 0 2 –5 7 6 11 25 0 2 –5 2 5 11 6 7 5 0 2 5 –9 2 5 11 6 7 9 02594 2 5 11 6 7 0 2 5 11 6 7 4 9 5 2 Stop since stack is empty Preorder Traversal: Initially push zero onto stack and then set root as vertex. if vertex ≠ 0 then return to step one otherwise exit. Then repeat the following steps until the stack is empty: 1. Pop and process the positive nodes (left nodes). The traversing ends after a vertex with no left child exists. 2. If zero is popped then exit. CURRENT VERTEX STACK 2 0 PROCESSED NODES 056 272 6 0 5 11 27265 11 05 2 7 2 6 5 11 05 2 7 2 6 5 11 5 09 2 7 2 6 5 11 5 9 0 2 7 2 6 5 11 5 9 4 0 2 7 2 6 5 11 5 9 4 Lecture Notes 162 REMARKS Stop since stack is empty Dept. Then repeat the following steps until the stack is empty: 1. if any and process each vertex.
2. as is the case with the unary minus operator. 3. Once an expression tree is constructed we can traverse it in three ways: • • • Inorder Traversal Preorder Traversal Postorder Traversal Figure 5. + + + a / b d + c d + (a) (a + b) + (c / d) c a (b) ((a + b) + c) + d b / + *  + a x + y * b c a (c) ((a) + (x + y)) / ((+b) * (c * a)) Figure 5. we pop pointers to two trees T1 and T2 from the stack (T1 is popped first) and form a new tree whose root is the operator and whose left and right children point to T2 and T1 respectively. It is also possible for a node to have only one child. and the other (non leaf) nodes contain operators.1 Expression Trees An expression tree can be generated for the infix and postfix expressions.4. we create a onenode tree and push a pointer to it onto a stack. of Information Technology .4. The leaves of an expression tree are operands. If the symbol is an operand. such as constants or variable names.4.1 shows some more expression trees that represent arithmetic expressions given in infix form.5. Expression Trees: Expression tree is a binary tree. If the symbol is an operator. A pointer to this new tree is then pushed onto the stack. Read the expression one symbol at a time. An algorithm to convert a postfix expression into an expression tree is as follows: 1. because all of the operations are binary. Lecture Notes 163 Dept.
and a pointer to it is pushed onto the stack. and e are read. of Information Technology . so we create onenode trees and push pointers to them onto a stack. c. so two pointers to trees are popped. and for each one–node tree is created and a pointer to the corresponding tree is pushed onto the stack. a new tree is formed. + a b Next. d. + c + a Lecture Notes + bb d 164 e Dept.Example 1: Construct an expression tree for the postfix expression: a b + c d e + * * Solution: The first two symbols are operands. a ‘+’ is read. so two trees are merged. a b Next. + a b c d e Now a ‘+’ is read.
of Information Technology . + + a * b c + d ee Finally.Continuing. Lecture Notes 165 Dept. + * * + a b c + d e e For the above tree: Inorder form of the expression: a + b * c * d + e Preorder form of the expression: * + a b * c + d e Postorder form of the expression: a b + c d e + * * Example 2: Construct an expression tree for the arithmetic expression: (A + B * C) – ((D * E + F) / G) Solution: First convert the infix expression into postfix notation. so we create onenode trees and pointers to three nodes pushed onto the stack. Postfix notation of the arithmetic expression is: A B C * + D E * F + G / The first three symbols are operands. two trees are merged. a ‘*’ is read. and a pointer to the final tree is left on the stack. so we pop two tree pointers and form a new tree with a ‘*’ as root. the last symbol is read.
+ A D * B Lecture Notes * E C 166 Dept. a ‘*’ is read. a ‘*’ is read. so two pointers to trees are popped. and for each one–node tree is created and a pointer to the corresponding tree is pushed onto the stack. a ‘+’ is read. and a pointer to it is pushed onto the stack. D and E are read. D + A E * B C Continuing. of Information Technology . a new tree is formed. a new tree is formed. and a pointer to it is pushed onto the stack. so we pop two tree pointers and form a new tree with a ‘*’ as root. + A * B C Next. A * C B Next.A B C Next. so two pointers to trees are popped.
1.4. 4. F * D G E Converting expressions with expression trees: Let us convert the following expressions from one type to another. Run inorder traversal on the tree. A. Create the expression tree from the postfix expression B. Create the expression tree from the prefix expression B. Prefix to Infix: The following algorithm works for the expressions whose infix form does not require parenthesis to override conventional precedence of operators. 3. Lecture Notes 167 Dept. when the last symbol is read. 2. Postfix to infix Postfix to prefix Prefix to infix Prefix to postfix Postfix to Infix: The following algorithm works for the expressions whose infix form does not require parenthesis to override conventional precedence of operators. A. the expression tree is as follows: + + A / + * B C 5. 2.Proceeding similar to the previous steps. finally. of Information Technology . Postfix to Prefix: The following algorithm works for the expressions to convert postfix to prefix: A. Run inorder traversal on the tree. These can be as follows: 1. Run preorder traversal on the tree. 3.1. Create the expression tree from the postfix expression B.
If the RCHILD(p) is normally equal to zero.J. In memory representation Threads and normal pointers are distinguished between as by adding two extra one bit fields LBIT and RBIT. of Information Technology . Create the expression tree from the prefix expression B. there are n+1 null links.4. For example. If we traverse T in inorder the nodes will be visited in the order H D I B E A F C G. Thornton. LBIT(P) = 1 LBIT(P) = 0 if LCHILD(P) is a normal pointer if LCHILD(P) is a Thread RBIT(P) = 1 RBIT(P) = 0 if RCHILD(P) is a normal pointer if RCHILD(P) is a Thread Lecture Notes 168 Dept. Their idea is to replace the null links by pointers called Threads to other nodes in the tree. If there are 2n total links. Threaded Binary Tree: The linked representation of any binary tree has more null links than actual pointers. node ‘E’ has a predecessor Thread which points to ‘B’ and a successor Thread which points to ‘A’. A null LCHILD link at node P is replaced by a pointer to the node which immediately precedes node P in inorder. Perlis and C. we will replace it by a pointer to the node which would be printed after P when traversing the tree in inorder. A clever way to make use of these null links has been devised by A. Run postorder traversal on the tree. Prefix to postfix: The following algorithm works for the expressions to convert postfix to prefix: A.5. For example. 5. Let us consider the tree: A C B E D G F I H The Threaded Tree corresponding to the above tree is: A B F E D H C G I The tree has 9 nodes and 10 null links which have been replaced by Threads.
In order to have no loose Threads we will assume a head node for all threaded binary trees. The tree T is the left subtree of the head node. Examples of binary search trees Lecture Notes 169 Dept. 2.2. Figure 5. 3.2. The left and right subtrees are also binary search trees. of Information Technology . If it is not empty then it satisfies the following properties: 1. 4. whereas figure 5. It may be empty.5. The keys in the right subtree are larger than the key in the root.5(a) is a binary search tree.6.5(b) is not a binary search tree.In the above figure two threads have been left dangling in LCHILD(H) and RCHILD(G).2. The keys in the left subtree are smaller than the key in the root. Every element has a key and no two elements have the same key. 16 16 12 11 20 14 12 19 11 13 14 13 Binary Search Tree 20 19 17 17 Not a Binary Search Tree (a) (b) Figure 5. B D H A 1 1 1 1 0 0 1  E 0 I 0 0 F C 0 1 0 G 0 0 Binary Search Tree: A binary search tree is a binary tree. LBIT LCHILD DATA RCHILD RBIT 1 1 1 1 0 5. The Complete memory representation for the tree is as follows.
Such a binary tree will not have a right subtree. the outdegree of every node is less than or equal to m.5.7. If the outdegree of every node is exactly equal to m or zero then the tree is called a full or complete mary tree. The general tree is also called as an mary tree. if any. Converting a mary tree (general tree) to a binary tree: There is a onetoone mapping between general ordered trees and binary trees. 170 Dept.e. we distinguish between left and right subtrees). For m = 2. which is immediately below the given node. we delete all the branches originating in every node except the left most branch. and the right son is the node to the immediate right of the given node on the same horizontal line.1. Each element in a binary tree has at most two subtrees. So. • We draw edges from a node to the node on the right. General Trees (mary tree): If in a tree. Conversion from general tree to binary can be done in two stages. 5. Stage 1: • As a first step. which is situated at the same level. every tree can be uniquely represented by a binary tree.7. the tree is called general tree. The subtrees of each element in a binary tree are ordered (i. of Information Technology . the trees are called binary and full binary trees. we choose its left and right sons in the following manner: • Lecture Notes The left son is the node. a forest can also be represented by a binary tree. Furthermore. The subtrees in a tree are unordered. Stage 2: • Once this is done then for any particular node. Differences between trees and binary trees: TREE BINARY TREE Each element in a tree can have any number of subtrees.
1 2 4 Lecture Notes 5 7 3 8 6 11 171 9 10 12 13 0 Dept. of Information Technology .Example 1: Convert the following ordered tree into a binary tree: 1 2 3 6 7 4 8 5 9 10 11 Solution: Stage 1 tree by using the above mentioned procedure is as follows: 1 2 6 3 7 4 8 5 9 10 11 Stage 2 tree by using the above mentioned procedure is as follows: 1 2 6 3 7 8 4 5 9 10 11 Example 2: Construct a unique binary tree from the given forest.
A B C D F E J G H Ge n e r a l t r e e T Lecture Notes 172 K L M P N Q Dept. Find the preorder traversal and the postorder traversal of T. 3. Find the corresponding binary tree T’. 2. inorder and postorder traversals of T’. Compare them with the preorder and postorder traversals obtained for T’ with the general tree T. Find the preorder.Solution: Stage 1 tree by using the above mentioned procedure is as follows: 1 2 4 5 7 3 8 9 6 11 10 12 13 Stage 2 tree by using the above mentioned procedure is as follows (binary tree representation of forest): 1 2 7 3 4 5 8 6 11 9 9 10 12 13 Example 3: For the general tree shown below: 1. 4. of Information Technology .
T2. Lecture Notes 173 Dept. ………. L. 2) Traverse the subtree T1. TM in postorder.. Postorder: 1) Traverse the subtree T1. T2. K. T2 and T3 such that: T1 consists of nodes B. ……. The The tree T has the root A and subtrees T1. Suppose T is a general tree with root R and subtrees T1.. T3 consists of nodes J.Solution: 1. Stage 1: The tree by using the abovementioned procedure is as follows: A B C F D E G J H B 5 K L M P N Q Stage 2: The binary tree by using the abovementioned procedure is as follows: A B C F D G 1E0 J H K L Bi n a rt t r e e T ’ M P N Q 2.. preorder traversal and the postorder traversal of T are: Preorder: 1) Process the root R. G and H. of Information Technology . ……. T2 consists of nodes F. P and Q. C. 2) Process the root R. N. TM. TM in preorder. T2. D and E. M.
D. F. G. Breadth first search or traversal. L. F. 1. Preorder: A. N. G. The inorder traversal of the binary tree T’ is identical to the postorder traversal of the general tree T. The preorder. L. Lecture Notes 174 Dept. M. (iv) Traverse T3 in preorder: Process nodes J. M. The preorder traversal of T is as follows: A. 5. (iv) Process root A. J. P. K. When the search necessarily involved the examination of every vertex in the tree. (ii) Traverse T2 in postorder: Process nodes G. K. Q. P.8. G. J. (iii) Traverse T3 in postorder: Process nodes K. L. F. M. (iii) Traverse T2 in preorder: Process nodes F.A. J. K. The postorder traversal of T consists of the following steps: (i) Traverse T1 in postorder: Process nodes C. B. N. Depth first search or traversal. 2. A Comparing the preorder and postorder traversals of T’ with the general tree T: We can observer that the preorder of the binary tree T’ is identical to the preorder of the general T. Q. Traversing of a tree can be done in two ways. E. J. F. P. A 3. H. L. M. P. B. Q. P. N. B. P. G. L. E. C. H. Search and Traversal Techniques for mary trees: Search involves visiting nodes in a tree in a systematic manner. H. K. B. K. D. E. K. N. F. P. J. M. G. D. H. E. E. L. M. of Information Technology . A Postorder: E. J. D. (ii) Traverse T1 in preorder: Process nodes B. C. N. Q. F. and may or may not result into a visit to all nodes. H. it is called the traversal. inorder and postorder traversals of the binary tree T’ are as follows: 4. N Inorder: C. The postorder traversal of T is as follows: C. Q. Q. C. E. There is no natural traversal of the general tree T which corresponds to the postorder traversal of its corresponding binary tree T’. The preorder traversal of T consists of the following steps: (i) Process root A. G. M. C. B. D. H. N B. D. H. D. B. Q.
G. so we back up to A again. J doesn’t have any successors. One simple way to implement depth first search is to use a stack data structure consisting of root node as a start state. then some successor of the start state. Breadthfirst search is named because it visits vertices across the entire breadth. H and G and the states considered were in order S. C. To illustrate this let us consider the tree shown below. D.1. E. It works very fine when search graphs are trees or lattices. C. F. To eliminate this keep a list of states previously visited. the state whose successor was ‘S’ originally. trying to reach a goal state. so we must back up to A and try its second successor. Depth first search: In Depth first search.2. then D. But B has no successors. If depth first search reaches a state S without successors. Disadvantages: 1. then it “backs up” that means it goes to the immediately previous state or predecessor formally. But D has no successors.8. then some successor of that and so on. we begin with root as a start state. Now ‘S’ has a second successor. the only goal state. But now we have tried all the successors of A and haven’t found the goal state G so we must back to ‘S’. C has one successor. Lecture Notes 175 Dept. J. C. But this doesn’t have any successors either. F. B. then A. 5. so we back up to H and try its second successor. and the first of H is J. The first successor of F is H. but can get struck in an infinite loop on graphs. And that’s G. 2. F. E. and never permit search to return to any of them. then some successor of that state. Breadth first search: Breadthfirst search starts at root node S and “discovers" which vertices are reachable from S. of Information Technology . Depth first search will first visit S. or if all the successors of a state S have been chosen (visited) and a goal state has not get been found. D A E ST A RT J B S H C F G GOAL K I Suppose S is the start and G is the only goal state. We cannot come up with shortest solution to the problem. B.5. This is because depth first search can travel around a cycle in the graph forever. so we back up to S again and choose its third successor. H. Breadthfirst search discovers vertices in increasing order of distance. So the solution path to the goal is S. A.8.
The density of the matrix is the number of nonzero elements divided by the total number of matrix elements. A. In large number of applications. and so on until we find a goal node. 5. 1) 1 (2. J and G and then stop because it has reached the goal node. sparse matrices are involved. One simple way to implement breadth first search is to use a queue data structure consisting of just a start state. Lecture Notes 176 Dept.To illustrate this let us consider the following tree: D A E ST A RT J B S H C F G GOAL K I Breadth first search finds states level by level. B. A. 2) 2 S= (3. Here we first check all the immediate successors of the start state. Suppose S is the start state and G is the goal state. F. reflecting the internal data structure. In the figure. C. I. E. and J. 3) 4 (1. The elements are sorted by columns. So breadth first search. H. G and K at level 4. The matrices with very low density are often good for use of the sparse format. Then all the immediate successors of these.9. D. Breadth first search does not have the danger of infinite loops as we consider states in order of increasing number of branches (level) from the start state. 4) 5 The printed output lists the nonzero elements of S. storing of null elements is nothing but wastage of memory. e and F at level 2. start state S is at level 0. H and I at level 3. So we should devise technique such that only nonnull elements will be stored. The matrix A produces: (3. A = ⎛0 ⎜ ⎜0 ⎜1 ⎜⎜ ⎝0 0 0 2 0 3 0 0 4 5⎞ ⎟ 0⎟ 0⎟ ⎟ 0 ⎟⎠ As far as the storage of a sparse matrix is concerned. together with their row and column indices. D. then all the immediate successors of these. 2) 3 (4. Sparse Matrices: A sparse matrix is a two–dimensional array having the value of majority elements as null. of Information Technology . will consider in order S. One approach is to use the linked list. B and C are at level 1. For example.
j < n . } Lecture Notes 177 Dept.i. clrscr(). j++) { scanf("%d". scanf("%d %d".. total_elements = m * n. for(i = 0. } } } if(total_zeros > total_elements/2 ) { printf("\n Given Matrix is Sparse Matrix.").h> # include <conio. total_zeros = 0. printf("\n Enter Number of rows and columns: "). &n). j < n .j. printf("\n Row \t Col \t Value "). j++) { if( matrix[i][j] != 0) { printf("\n %d \t %d \t %d". i++) { for( j = 0. of Information Technology . i < m . i. j.matrix[i][j]). n. */ # include <stdio. m. for(i = 0. i++) { for( j = 0. total_elements. } } } } else printf("\n Given Matrix is Not a Sparse Matrix.h> main() { int matrix[20][20].."). printf("\n Enter data for sparse matrix: ").The program to represent sparse matrix: /* Check whether the given matrix is sparse matrix or not. &matrix[i][j]). if( matrix[i][j] == 0) { total_zeros++. i < m . if so then print in alternative form for storage. printf("\n The Representaion of Sparse Matrix is: \n").&m.
Write a “C” function to compute the internal path length of a binary tree. Draw all the possible binary trees that have four leaves and all the nonleaf nodes have no children. 77. 6. 5. b. How many different binary trees can be made from three nodes that contain the key value 1. Lecture Notes 178 Dept. of Information Technology . 10. The maximum number of nodes in any level of a binary tree is also called the width of the tree. Show how the (original) tree would look after the insertion of nodes containing 63. d. 59 and 47? h. 9 and 10 (in that order). 4. Write a “C” function to compute the maximum number of nodes in any level of a binary tree. 7. 2. Construct two binary trees so that their postorder traversal sequences are the same. 76. Prove that the inorder and postorder traversal sequences of a binary tree uniquely characterize the binary tree. a. e. a. Prove that every node in a tree except the root node has a unique parent.EXCERCISES 1. 8. Draw the binary search tree whose elements are inserted in the following order: 50 72 96 94 107 26 12 11 9 2 10 25 51 16 17 95 b. 48. Show what would be printed by each of the following. c. What is the height of the tree? What nodes are on level? Which levels have the maximum number of nodes that they could contain? What is the maximum height of a binary search tree containing these nodes? Draw such a tree? What is the minimum height of a binary search tree containing these nodes? Draw such a tree? g. Write a “C” function to count the number of leaf nodes in a binary tree. Write a “C” function to determine the height of a binary tree. 9. 11. f. and 3? 2. 13. 12. Write a “C” function to reconstruct a binary tree from its postorder and inorder traversal sequences. Write a “C” function to reconstruct a binary tree from its preorder and inorder traversal sequences. Show how the tree would look after the deletion of 29. Write a “C” function to swap a binary tree. Write a “C” function to compute the external path length of a binary tree. An inorder traversal of the tree A postorder traversal of the tree A preorder traversal of the tree 3.
Inorder: Level order: gdhbeiafjc abcdefghij Build the binary tree from the given traversal techniques: A. Inorder: Preorder: gdhbeiafjc abdgheicfj B. EACKFHDBG FAEKCDHGB Convert the following general tree represented as a binary tree: 3 1 12 7 15 5 10 13 14 11 4 9 2 16 Lecture Notes 179 8 6 17 Dept. Inorder: Preorder: n1 n2 n3 n4 n5 n6 n7 n8 n9 n6 n2 n1 n4 n3 n5 n9 n7 n8 B. Inorder: Level order: n1 n2 n3 n4 n5 n6 n7 n8 n9 n6 n2 n9 n1 n4 n7 n3 n5 n8 Build the binary tree for the given inorder and preorder traversals: Inorder: Preorder: 17. Build the binary tree from the given traversal techniques: A. of Information Technology . 15.14. 16. Inorder: Postorder: n1 n2 n3 n4 n5 n6 n7 n8 n9 n1 n3 n5 n4 n2 n8 n7 n9 n6 C. Inorder: Postorder: gdhbeiafjc ghdiebjfca C.
the preorder traversal sequence is: A. H D I B E A F C J G K B. Parent node C. of Information Technology . A B D H I E C F G J K [ C ] 8. Leaf node B. Full binary tree D. H I D E B F J K G C A D. A B C D E F G H I J K C. the inorder traversal sequence is: A. consists of________ edges. Adjacency list C. For the Binary tree shown in fig.Multiple Choice Questions 1. A B D H I E C F G J K [ B ] Lecture Notes 180 Dept. A tree with n vertices. H D I B E A F C J G K B. Incidence matrix D. 1. 1. nonleaf node D. log n [ A ] 6. n – 1 C. A B C D E F G H I J K C. Complete binary tree C. Adjacency matrix B. A B C D E F G H I J K C. H I D E B F J K G C A D. Strictly binary tree B. n B. Binary search tree [ B ] 3. For the Binary tree shown in fig. 2n D. Root node D. A. For the Binary tree shown in fig. The node that has no children is referred as: A. Sibblings B. leaf node [ C ] 5. H D I B E A F C J G K B. The maximum number of nodes at any level is: A. 1. A B D H I E C F G J K [ D ] 9. adjacent node C. A binary tree in which all the leaves are on the same level is called as: A. Sibblings [ C ] 2. 2n [ B ] A B D H C E I FI G UR E 1 F G J K 7. the postorder traversal sequence is: A. H I D E B F J K G C A D.2 D. n C. How can the graphs be represented? A. The children of a same parent node are called as: A. All of the above [ C ] 4. n + 1 B. n .
For the figure 2 shown above. none of the above [ B ] 11. D) then (D. G) B. G) then (B. The tree is complete but not full. which statement is correct? A. how many of the nodes have at least one sibling? A. 4 B. Which is the correct order for Kruskal’s minimum spanning tree algorithm to add edges to the minimum spanning tree for the figure 2 shown above: A. what is the depth of the tree? A. E) then (F. F) then (D. 8 [ A 14. 2 D. 4 D. 6 B. For the figure 3. For the figure 3. How many descendants does the root have? A. 6 D. 8 [ B ] 13. For the figure 3. 3 D. 2 C. 48 B. 8 [ D ] 15. C) C. of Information Technology ] . The tree is both full and complete. D. 68 D. 7 B. For the figure 3. The tree is neither complete nor full. C. [ A ] Lecture Notes 181 Dept. both A and B D. D) then (E. B. D) then (D.23 28 B 9 D 25 A 15 4 1 36 C Node 20 A E 16 3 F G 17 Adjacency List BCD B ADE C ADF D ABCEFG E BDG F CDG G FDE FIGURE 2 and its adjacency list 10. The tree is full but not complete. 57 C. 32 [ A ] 14 2 1 FIGURE 3 11 3 10 7 30 40 12. C) then (A. 5 C. how many leaves does it have? A. 2 C. (A. 4 B. For the figure 3. (A. 0 C. E) then (C. the cost of the minimal spanning tree is: A. G) then (A. B) then (A. 8 [ B ] 16.
4 D. A. 0 C. What is the order of nodes visited using a preorder traversal? A. Every node has at most two children. Consider the node of a complete binary tree whose value is stored in data[i] for an array implementation. C. Every binary tree is either complete or full. 1 2 is a tree in the box at the top of this section. data[i+1] C. Every nonempty tree has exactly one root node. Every nonroot node has exactly one parent. No binary tree is both complete and full. Suppose T is a binary tree with 14 nodes. B. [ C ] 22. Every full binary tree is also a complete binary tree. [ A ] 24. There is a tree in the box at the top of this section. 5 [ B ] 23. D. What is the minimum possible depth of T? A. 14 2 1 3 11 10 7 30 40 [ ] 18. data[i+2] D. 3 D. 4 B. data[2*i + 2] [ C ] 14 2 16 1 Figure 4 5 4 Lecture Notes 182 Dept. 1 2 B. 1 2 3 14 7 10 11 40 30 D. Every binary tree has at least one node. 14 2 1 3 11 10 7 30 40 [ ] 19. 1 2 B. Select the one true statement. 1 3 2 7 10 40 30 11 14 3 14 7 10 11 40 30 D. 1 3 2 7 10 40 30 11 14 B. 1 2 is a tree in the box at the top of this section. There nodes A. where will the right child's value be stored? A. 15 [ D ] 21. 14 2 1 3 11 10 7 30 40 [ ] 20. What is the minimum number of nodes in a full binary tree with depth 3? A. What is the order of visited using an inorder traversal? 3 7 10 11 14 30 40 C. 1 2 3 7 10 11 14 30 40 C. Select the one FALSE statement about binary trees: A. D. data[2*i + 1] B. There nodes A. 1 3 2 7 10 40 30 11 14 3 14 7 10 11 40 30 D. 8 B. What is the order of visited using a postorder traversal? 3 7 10 11 14 30 40 C. 3 C. B.17. Every complete binary tree is also a full binary tree. of Information Technology . C. If this node has a right child.
3 7 3 6 D. Inorder. 5 3 7 2 4 6 B. Which among the following is not a binary search tree? [ C ] A. will produce the same sequence of node names? A. C. Postorder C. Postorder. 4 [ D ] A B G C Tr e e 2 D E G F E F I H J I Tr e e 1 C D H A B J 26. 1 D.25. For the binary search tree shown in figure 4. Inorder B. Postorder D. Inorder [ C ] 27. replacing it with something from the left subtree. 5 B. Preorder. What will be the new root? A. 16 C. 2 E. Postorder. of Information Technology . Suppose we remove the root. 5 7 5 14 2 2 16 6 1 5 4 Lecture Notes 183 Dept. Which traversals of tree 1 and tree 2.
11 → 7 B. ⎣ log2 n ⎦ + 1 B. H. B. 2k A. B. F. H. after deleting 23 from the binary search tree what parent → child pair does not occur in the tree? A. of Information Technology . 2n [ C ] 32. H. 11 C. Queue C. F. Lecture Notes 184 Dept. If the inorder and preorder traversal of a binary tree are D. B. none of the above B. D. For the binary search tree shown in figure 5. E. 14 [ ] 29. D. E. G. 25 → 27 C. F. E. log n C. 27 → 11 D. n2 D. B. C. 2d k D. C respectively then. G. D.23 11 27 7 6 17 9 25 FI G UR E 5 14 28. E D. B. E. G. A [ A ] 33. The data structure used by level order traversal of binary tree is: A. A. F. none of the above [ A ] 30. F. B. 7 → 9 The number of nodes in a complete binary tree of depth d is: C. linked list B. D. H. F. For the binary search tree shown in figure 5. E. the postorder traversal of that tree is: A. C. C. C.1 [ B ] [ B ] 31. A. Stack D. The depth of a complete binary tree with n nodes is: A. G. 27 B. after deleting 23 from the binary search tree what node will be at the root? A. G. G. A C. D. 25 D. C and A. 2 . A B. H. H.
Introduction to Graphs: Graph G is a pair (V. arrow head) is a directed edge.5.. the digraph shown in figure 6. e = E.5. if for each pair (u. An edge with an orientation (i. If all the edges in a graph are undirected.(a) and figure 6.1 (e) is strongly connected. where V is a finite set of vertices and E is a finite set of edges.Chapter 6 Graphs 6.1. while an edge with no orientation is our undirected edge. The graph in figure 6. For example. We will often denote n = V. Figure 6.(d) are complete graphs.1. in which the vertices are represented by circles and the edges by lines. A directed graph is also called as digraph. v) for nodes in G there is a path from u to v and also a path from v to u. then the graph is an undirected graph. then the graph is a directed graph.5. G is said to be unilaterally connected if for any pair (u.1(a) is an undirected graph. A directed graph G is said to be connected.1. A graph is generally displayed as figure 6.1(b) is a directed graph. v) of nodes in G there is a path from u to v or a path from v to u. E). On the other hand. A graph G is connected if and only if there is a simple path between any two nodes in G.1. The graph of figure 6. For example.5.e. If all the edges are directed. B D A C E E G C (a) v4 v3 v4 (e) v2 (b) v1 v2 v4 D F v1 (d) v1 B A v3 v1 v1 v2 v4 (f) v3 v2 v2 v3 (c) v3 (g) v4 v5 v6 v7 Figure 6. A graph G is said to be complete if every node a in G is adjacent to every other node v in G. or strongly connected. of Information Technology . A complete graph with n nodes will have n(n1)/2 edges. The graph which has such function assigned is called weighted graph.5.1 Various Graphs We can assign weight function to the edges: wG(e) is a weight of edge e ∈ E.5. Lecture Notes 185 Dept.5.
1(a).5. Let T be a spanning tree of a graph G. The number of outgoing edges from a vertex is called outdegree (denote outdeg(v)).1(d). figure 6. T2 and T3. v2.1 (g) are acyclic graphs. vi+1) ε E. Lecture Notes 186 Dept. For example.5. .1(f). If a graph (digraph) does not have any cycle then it is called acyclic graph. A Forest is a set of disjoint trees. If any edge is removed from T. A P B T1 C D E Q X Y R Z F T2 T3 A Forest F A graph that has either self loop or parallel edges or both is called multigraph. 3. Then 1. If we remove the root node of a given tree then it becomes forest.1 (f) and figure 6. . then T becomes disconnected. there is a cycle in figure 6. A single graph can have multiple spanning trees. vk). The following figure shows a forest F that consists of three trees T1.The number of incoming edges to a vertex v is called in–degree of the vertex (denote indeg(v)). let us consider the digraph shown in figure 6. E’) is a subgraph of graph G = (V. Number of edges in T is n1.5. For example. Tree is a connected acyclic graph (there aren’t any sequences of edges that go around in a loop). A graph G’ = (V’. (vi. A spanning tree of a graph G = (V. the graphs of figure 6. then the new graph will contain a cycle.5. Any two vertices in T are connected by a unique simple path. If we add any edge into T. E) is a tree that contains all vertices of V and is a subgraph of G. E) iff V’ ⊆ V and E’ ⊆ E. . of Information Technology . where for all i. . For example. . 4. A path is simple if all vertices in the path are distinct.1(c) and figure 6.5.5. indegree(v1) = 2 outdegree(v1) = 1 indegree(v2) = 2 outdegree(v2) = 0 A path is a sequence of vertices (v1. 2. If there is a path containing one or more edges which starts from a vertex Vi and terminates into the same vertex then the path is known as a cycle. .
The adjacency matrix is also useful to store multigraph as well as weighted graph. • Incidence matrix. while it may be asymmetric if the graph is directed.2(a).2(b) shows the adjacency matrix representation of the graph G1 shown in figure 6.3(b) shows the cost adjacency matrix representation of the graph G2 shown in figure 6.5.2. In case of weighted graph. the entry will be between number of edges between two vertices. the entries are weights of the edges between the vertices.5.5. instead of entry 0 or 1. of Information Technology . Figure 6. G2: 4 B 3 1 2 A 6 (a) D C 2 4 2 E 2 4 1 1 F G (b) A B C D E F G A 0 3 6 ∝ ∝ ∝ ∝ B 3 0 2 4 ∝ ∝ ∝ C 6 2 0 1 4 2 ∝ D ∝ 4 1 0 2 ∝ 4 E ∝ ∝ 4 2 0 2 1 F ∝ ∝ 2 ∝ 2 0 1 G ∝ ∝ ∝ 4 1 1 0 Figure 6. Adjacency matrix: In this representation.5. They are: • Adjacency matrix. a i. • Adjacency List. A graph and its Adjacency matrix Figure 6.2. j 1 2 G1: 3 4 (a) 5 (b) 1 2 3 4 5 1 0 0 0 0 0 2 1 0 0 0 0 3 1 1 0 0 1 4 0 1 1 0 1 5 1 1 0 0 0 Figure 6. In case of multigraph representation. the adjacency matrix of a graph G is a two dimensional n x n matrix. Representation of Graphs: There are two ways of representing digraphs.5.3 Weighted graph and its Cost adjacency matrix Lecture Notes 187 Dept. where ⎧ 1 if there is an edge from v i to v j = ⎨ ⎩ 0 otherwise The matrix is symmetric in case of undirected graph. The adjacency matrix for a weighted graph is called as cost adjacency matrix.6.3(a). This matrix is also called as Boolean matrix or bit matrix.5.j). say A = (ai.
c B a d b A g (a) D C f e h k E j i G l F (b) A B C D E F G a 1 1 0 0 0 0 0 b 0 1 1 0 0 0 0 c 0 1 0 1 0 0 0 d 0 0 1 1 0 0 0 e 0 0 0 1 1 0 0 f 0 0 0 1 0 0 1 g 1 0 1 0 0 0 0 h 0 0 1 0 1 0 0 i 0 0 0 0 1 0 1 j 0 0 0 0 1 1 0 k 0 0 1 0 0 1 0 l 0 0 0 0 0 1 1 Figure 6. Such a matrix is called as vertexedge incidence matrix or simply incidence matrix. j ⎧ 1 if there is an edge j incident to v i = ⎨ ⎩ 0 otherwise Here. If the edges have weights then these weights may also be stored in the linked list elements.5.4 Graph and its incidence matrix Figure 6. An array Adj[1. the n rows of the adjacency matrix are represented as n linked lists.5. Adj[v] points to a linked list containing the vertices which are adjacent to v (i. Lecture Notes 188 Dept. 2.4 Adjacency matrix and adjacency list Incidence Matrix: In this representation. the vertices that can be reached from v by a single edge).Adjacency List: In this representation.5. . e edges and no self loops.e. if G is a graph with n vertices.4(a). n rows correspond to n vertices and e columns correspond to e edges. of Information Technology . n] of pointers where for 1 < v < n.j).5. 1 2 3 1 1 1 1 2 0 0 3 0 1 1 1 1 2 3 0 3 2 (a) Adjacency Matrix 2 3 (b) Adjacency List Figure 6. . say A = (ai.5. . where a i.5. For the graph G in figure 6.4 (b).4(a). . then incidence matrix A is defined as an n by e matrix. . the adjacency list in shown in figure 6.4(b) shows the incidence matrix representation of the graph G1 shown in figure 6.
Weight of a spanning tree w(T) is the sum of weights of all edges in T. i. Minimum spanning tree. Minimum Spanning Tree (MST): A spanning tree for a connected graph is a tree whose vertex set is the same as the vertex set of the given graph. The vertices of the graph would represent cities. For instance. but both eventually end up with the MST. Both algorithms differ in their methodology.3. thereby connecting everyone at a minimum cost. of Information Technology . Lecture Notes 189 Dept. wish to be connected together in a telephone network. MST can be applied to optimize airline routes by finding the least costly paths with no cycles. a group of individuals. Minimum spanning tree (MST) is a spanning tree with the smallest possible weight. and Prim’s algorithm uses vertex connections in determining the MST. Prim’s algorithm. Although MST cannot do anything about the distance from one connection to another. Kruskal's algorithm uses edges. • Another useful application of MST would be finding airline routes. can be constructed using any of the following two algorithms: 1. and the edges would represent routes between the cities. it can be used to determine the least cost paths with no cycles in this network. Kruskal’s algorithm and 2. who are separated by varying distances.e.6.. In Prim’s algorithm at any instance of output it represents tree whereas in Kruskal’s algorithm at any instance of output it may represent tree or not. Example: G: A gr a p h G: T hr e e ( of ma n y p o s s i b l e) s p a n n i n g t r e e s f r o m gr a p h G: 2 2 4 G: 3 3 5 6 1 1 A w e i g ht e d gr a p h G: T h e mi n i m a l s p a n n i n g t r e e f r o m w e i g ht e d gr a p h G: Let's consider a couple of realworld examples on minimum spanning tree: • One practical application of a MST would be in the design of a network. and whose edge set is a subset of the edge set of the given graph. any connected graph will have a spanning tree.
5.1 edges and E is not empty otherwise. Sometimes two or more edges may have the same cost. Make the tree T empty. 2) (3. Delete (v. 6) Lecture Notes 190 Dept. while avoiding the creation of cycles. Kruskal’s Algorithm This is a greedy algorithm. A greedy algorithm chooses some local optimum (i. which will always be the minimum cost.1. Different MST’s may result. If (v. keep on adding the shortest (least cost) edge. until (n . proceed to step 6. w) to T else discard (v. w) does not create a cycle in T then Add (v. Example 1: Construct the minimal spanning tree for the graph shown below: 10 1 50 2 45 40 30 3 35 25 4 5 55 20 15 6 Arrange all the edges in the increasing order of their costs: Cost 10 15 20 25 30 35 40 45 50 55 Edge (1. 5) (2.3. 6) (4.1 edges then print no spanning tree. does not matter. Choose an edge (v. of Information Technology . 5) (1. w) from E. 6) (1. but they will all have the same total cost. picking an edge with the least weight in a MST). 3) (5. 4. w) from E of lowest cost.e. The order in which the edges are chosen. 4) (3. 5) (2. w) 6.6. Kruskal’s Algorithm for minimal spanning tree is as follows: 1. in this case. If T contains fewer than n . Kruskal's algorithm works as follows: Take a graph with 'n' vertices. 4 and 5 as long as T contains less than n . 6) (2. Repeat the steps 3. 2. 3.1) edges have been added.
2 3 4 5 6 (2. 2) 10 STAGES IN KRUSKAL’S ALGORITHM 1 The edge between vertices 1 and 2 is the first edge selected. 6) 25 1 The edge between vertices 2 and 6 is considered next and included in the tree. 5) 35 The edge between the vertices 1 and 4 is discarded as its inclusion creates a cycle. 6) 15 1 Next. 3 5 The cost of the minimal spanning tree is 105. 6) 20 1 The edge between vertices 4 and 6 is next included in the tree. This completes the tree. 6 Lecture Notes 191 Dept. the edge between vertices 3 and 6 is selected and included in the tree.The stages in Kruskal’s algorithm for minimal spanning tree is as follows: EDGE COST (1. Reject 1 2 4 Finally. 2 3 4 REMARKS 5 6 (3. It is included in the spanning tree. 2 3 4 5 6 (4. 2 3 4 5 6 (1. the edge between vertices 3 and 5 is considered and included in the tree built. 4) 30 (3. of Information Technology .
6) (3. 5) (5. 2 6 3 7 5 4 (2. 2 6 3 7 5 4 Lecture Notes 192 Dept. 4) 1 12 Next. 7) 1 14 The edge between vertices 2 and 7 is next included in the tree. 2 6 3 7 5 4 (3. It is included in the spanning tree. 7) (2. the edge between vertices 3 and 4 is selected and included in the tree. 7) (4.Example 2: Construct the minimal spanning tree for the graph shown below: 28 1 10 2 14 6 24 25 16 7 3 18 5 22 12 4 Solution: Arrange all the edges in the increasing order of their costs: Cost 10 12 14 16 18 22 24 25 28 Edge (1. of Information Technology . 6) (1. 6) 10 STAGES IN KRUSKAL’S ALGORITHM 1 REMARKS The edge between vertices 1 and 6 is the first edge selected. 7) (5. 3) (4. 4) (2. 2) The stages in Kruskal’s algorithm for minimal spanning tree is as follows: EDGE COST (1.
we must always add a new vertex for which the cost of the new edge is as small as possible. weights other than costs). This completes the tree. we must be selective . Minimal cost spanning tree is a spanning tree for which the sum of the edge labels is as small as possible The slight modification of the spanning tree algorithm yields a very simple algorithm for finding an MST. MINIMUMCOST SPANNING TREES: PRIM'S ALGORITHM A given graph can have many spanning trees. 5) 22 The edge between the vertices 4 and 7 is discarded as its inclusion creates a cycle. 6) 25 The edge between the vertices 5 and 7 is discarded as its inclusion creates a cycle. Minimal cost spanning tree is a connected undirected graph G in which each edge is labeled with a number (edge labels may signify lengths. 5 4 6. This simple modified algorithm of spanning tree is called prim's algorithm for finding an Minimal cost spanning tree. Reject 1 Finally. Prim's algorithm is an example of a greedy algorithm. 2 6 3 7 5 4 (4. Reject 1 The edge between vertices 4 and 7 is considered next and included in the tree. 3) 1 16 The edge between vertices 2 and 3 is next included in the tree. This tree is called as minimal cost spanning tree. 2 6 3 7 5 4 (5. 2 6 3 7 The cost of the minimal spanning tree is 99. Lecture Notes 193 Dept. we have to select a cheapest one. 7) 24 (5. To find a Minimal cost spanning tree.2.3.(2. any vertex not in the tree but connected to it by an edge can be added. of Information Technology . From these many spanning trees. In the spanning tree algorithm. 7) 18 (4. the edge between vertices 5 and 6 is considered and included in the tree built.
k]) then near [i] := l. l]. 1:2]. l] < cost [i. t) { Let (k. near [j]]. j])) then near [k] := j. 1]. n. near [k] :=near [l] := 0. { Let j be an index such that near [j] ≠ 0 and cost [j. t [i. 2] := near [j]. (t [i.1 do // Find n . A minimum spanning tree is computed and stored as a set of edges in the array t [1:n1. for i :=1 to n do // Initialize near if (cost [i. 1] := k. if ((near [k] ≠ 0) and (cost [k.Prim’s Algorithm: E is the set of edges in G. cost [1:n. } EXAMPLE: Use Prim’s Algorithm to find a minimal spanning tree for the graph shown below starting with the vertex A. l) be an edge of minimum cost in E. 2] := l. 1:n] is the cost adjacency matrix of an n vertex graph such that cost [i. cost. t [i. mincost := cost [k.2 additional edges for t. near [j] := 0 for k:= 1 to n do // Update near[]. } return mincost. t [1. 2]) is an edge in the minimumcost spanning tree. mincost := mincost + cost [j. j) exists. j] is either a positive real number or ∝ if no edge (i. Algorithm Prim (E. t [i. for i:=2 to n . else near [i] := k. near [k]] > cost [k. 1] := j. t [1. 4 B 3 2 D 1 2 E 4 A 6 C 4 1 2 2 G F 1 Solution: ⎛0 ⎜ ⎜3 ⎜6 ⎜ The cost adjacency matrix is ⎜ ∞ ⎜ ⎜∞ ⎜∞ ⎜⎜ ⎝∞ Lecture Notes 3 6 ∞ ∞ ∞ 0 2 4 ∞ ∞ 2 0 1 4 2 4 1 0 2 ∞ ∞ 4 2 0 2 ∞ 2 ∞ 2 0 ∞ ∞ 4 1 1 194 ∞⎞ ⎟ ∞⎟ ∞⎟ ⎟ 4⎟ ⎟ 1⎟ 1⎟ ⎟ 0 ⎟⎠ Dept. of Information Technology . The final cost is returned. near [j]] is minimum.
Next A 0 0 * B 0 3 A C 0 2 B D 0 1 C E 1 2 D F 1 2 C G 1 4 D Vertex Status Dist. of Information Technology . Next A 0 0 * B 0 3 A C 0 2 B D 0 1 C E 1 2 D F 0 2 C G 1 1 E Step 2: B 3 A 0 2 C 44 D ∝ E ∝ F 1 D 4 E ∝ G Step 3: B 3 A 0 ∝ 2 C 2 F 1 D 2 E 2 F 1 D 2 E 2 F G Step 4: A 0 2 C 4 G Step 5: B A 0 3 2 1 G C Lecture Notes 195 Dept. Next A 0 0 * B 0 3 A C 0 2 B D 1 1 C E 1 4 C F 1 2 C G 1 ∝ A Vertex Status Dist. Next A 0 0 * B 0 3 A C 1 2 B D 1 4 B E 1 ∝ A F 1 ∝ A G 1 ∝ A Vertex Status Dist.The stepwise progress of the prim’s algorithm is as follows: Step 1: B A 3 ∝ D ∝ E ∝ F 6 0 C ∝ G Vertex Status Dist. Next A 0 0 * B 1 3 A C 1 6 A D 1 ∝ A E 1 ∝ A F 1 ∝ A G 1 ∝ A Vertex Status Dist.
1 D 2 E 1 F 1 Reachability Matrix (Warshall’s Algorithm): Warshall’s algorithm requires knowing which edges exist and which does not. A2. It doesn’t need to know the lengths of the edges in the given directed graph. which are connected and zero entry indicates a pair. y]) Lecture Notes 196  (1) Dept. Next A 0 0 * B 0 3 A C 0 2 B D 0 1 C E 0 2 D F 1 1 G G 0 1 E G Vertex Status Dist. A one entry in the matrix Ai will correspond to the existence of i–paths and zero entry will correspond to nonexistence. Next A 0 0 * B 0 3 A C 0 2 B D 0 1 C E 0 2 D F 0 1 G G 0 1 E D 1 E 1 F Step 7: B A 0 3 2 C 6.4. in which a ‘1’ indicates the existence of an edge and ‘0’ indicates nonexistence. . which is called A0. the final matrix An. and then updates the matrix ‘n’ times. In warshall’s algorithm the matrix Ai contains information about the existence of i–paths. of Information Technology . Thus when the algorithm stops. i] ٨ Ai1 [i. which are not. This matrix is called a reachability matrix or path matrix for the graph. This information is conveniently displayed by adjacency matrix for the graph. producing matrices called A1. A d j ac e nc y M at r i x W a r s h a l l’ s A l g or it h m A l l P a ir s Rec h a b i l it y M at r i x It begins with the adjacency matrix for the given graph. It is also called the transitive closure of the original adjacency matrix.Step 6: B A 1 3 0 2 2 C G Vertex Status Dist. y] = Ai1 [x. An and then stops. . y] ۷ (Ai1 [x. . A one entry indicates a pair of vertices. . The update rule for computing Ai from Ai1 in warshall’s algorithm is: Ai [x. contains the desired connectivity information. . .
2] = A1[3. 2] ۷ (A1[2. 4] ۷ (A0[1. 4] = A0[3. 1] ۷ (A1[3. 1] ٨ A0[1. 2] ۷ (A0[3. 1] ٨ A0[1. 4]) = 0 ۷ (1 ٨ 1) = 1 A2[2. but again we need to update the 0 entries. 1] = A1[2. 2] ٨ A1[2. 1]) = 0 ۷ (0 ٨ 0) = 0 A1[2. 1] ۷ (A1[2. 2]) = 0 ۷ (0 ٨ 0) = 0 Lecture Notes 197 Dept. 2] ٨ A1[2.Example 1: Use warshall’s algorithm to calculate the reachability matrix for the graph: 4 1 4 5 6 7 11 1 2 3 7 We begin with the adjacency matrix of the graph ‘A0’ 1 ⎛0 ⎜ 2 ⎜0 A0 = ⎜ 3 0 ⎜ 4 ⎜⎝1 1 1 0 1 0 0 1 1 0⎞ ⎟ 1⎟ 0⎟ ⎟ 0 ⎟⎠ The first step is to compute ‘A1’ matrix. A2[1. 3] = A0[3. 2] ۷ (A0[2. 1] ٨ A0[1. 4] ۷ (A0[4. 1] ۷ (A0[3. 1] = A0[2. 4]) = 0 ۷ (0 ٨ 0) = 0 A1[4. A1[1. 4]) = 0 ۷ (1 ٨ 0) = 0 1 ⎛0 ⎜ 2 ⎜0 A1 = ⎜ 3 0 ⎜ 4 ⎜⎝1 1 1 0 1 0 0 1 1 0⎞ ⎟ 1⎟ 0⎟ ⎟ 0 ⎟⎠ Next. 1] = A0[3. 2] ۷ (A1[3. 1] ۷ (A1[1. 1] ٨ A0[1. since in Boolean algebra 1 + (anything) = 1. 4] = A0[1. 1]) = 0 ۷ (0 ٨ 0) = 0 A1[1. 2] ٨ A1[2. 2] = A0[3. 4] ۷ (A1[1. Before doing so. 1] ٨ A0[1. 1]) = 0 ۷ (0 ٨ 0) = 0 A1[3. 2] = A0[2. 1]) = 0 ۷ (1 ٨ 0) = 0 A2[1. 3] ۷ (A0[3. 1] ٨ A0[1. 4]) = 0 ۷ (0 ٨ 0) = 0 A1[2. there are only nine entries in A0 that need to be updated. 1] ۷ (A0[1. A2 must be calculated from A1. 1] = A0[1. 2]) = 0 ۷ (0 ٨ 1) = 0 A1[3. Since these are only nine zero entries in A0. 1] = A1[3. 2]) = 0 ۷ (0 ٨ 1) = 0 A1[3. 1] ٨ A0[1. 2] = A1[2. 1]) = 0 ۷ (0 ٨ 0) = 0 A2[3. of Information Technology . 1] = A1[1. 4] ۷ (A0[3. To do so we will use the updating rule – (1). 4] = A0[4. 2] ٨ A1[2. 1] ٨ A0[1. 1] ٨ A0[1. 2] ٨ A1[2. 4] = A1[1. 1]) = 0 ۷ (0 ٨ 0) = 0 A2[2. 2] ٨ A1[2. we notice that only one entry in A0 must remain one in A1. 3]) = 0 ۷ (0 ٨ 1) = 0 A1[3. 1] ۷ (A0[2. 2]) = 0 ۷ (0 ٨ 0) = 0 A2[3.
3] ٨ A2[3. 2] ۷ (A3 [3. 1] ۷ (A2[2. 4] ۷ (A1[4. 2]) = 0 ۷ (0 ٨ 0) = 0 A3[3. 3] ٨ A2[3. 1]) = 0 ۷ (1 ٨ 0) = 0 A3[2. 4]) = 0 ۷ (0 ٨ 1) = 0 ۷ 0 = 0 1 ⎛1 ⎜ 2 ⎜1 A4 = ⎜ 3 0 ⎜ 4 ⎜⎝1 1 1 1 1 0 0 1 1 1⎞ ⎟ 1⎟ 0⎟ ⎟ 1⎟⎠ Note that according to the algorithm vertex 3 is not reachable from itself 1. 3] = A1[3. 1] ۷ (A3 [3. 1] ۷ (A2[1. 3] ٨ A2[3. 2] ٨ A1[2. A3[1. 3] ٨ A2[3. 1]) = 0 ۷ (0 ٨ 1) = 0 ۷ 0 = 0 A4[3. 1]) = 0 ۷ (1 ٨ 0) = 0 A3[2. 4] ٨ A3 [4. 3] ۷ (A2[3. 4] = A2[3. 4] ۷ (A2[3. there is no path from vertex 3 back to itself. 4] ٨ A3 [4. 1] = A3 [2. 4] ٨ A3 [4. 2] ۷ (A2[3. 2]) = 0 ۷ (0 ٨ 1) = 0 ۷ 0 = 0 A4[3. 2] = A2[3. 1] = A3 [3. 4] ٨ A3 [4. 4] = A1[4. and so to compute A3. 4] ٨ A3 [4. 4] ۷ (A1[3. 2] ٨ A1[2. 4] = A1[3. 3]) = 0 ۷ (0 ٨ 1) = 0 A2[3. 3]) = 0 ۷ (0 ٨ 1) = 0 ۷ 0 = 0 A4[3. 1] ۷ (A3 [1. 1]) = 0 ۷ (1 ٨ 1) = 0 ۷ 1 = 1 A4[2. A4[1. 1]) = 0 ۷ (0 ٨ 0) = 0 A3[3. 3] ٨ A2[3. 3] ۷ (A3 [3. This matrix is the reachability matrix for the graph. 2] ۷ (A2[2. 1] ۷ (A3 [2. we need to do only seven computations. 2] ٨ A1[2. 1] = A2[2. 3] = A2[3. 3] ۷ (A1[3. 1] ۷ (A2[3. This is because as can be seen in the graph. 4] ٨ A3 [4. 1] = A2[1. 1] = A2[3. 4] ۷ (A3 [3. we use the update rule to calculate A4 and stop. 4] ٨ A3 [4. 3] = A3 [3.A2[3. 3] ٨ A2[3. 4]) = 0 ۷ (0 ٨ 1) = 0 A2[4. of Information Technology . Lecture Notes 198 Dept. 3]) = 0 ۷ (0 ٨ 0) = 0 A3[3. 2] = A2[2. 2]) = 0 ۷ (1 ٨ 1) = 0 ۷ 1 = 1 A4[3. 2]) = 0 ۷ (1 ٨ 0) = 0 A3[3. 2] ۷ (A3 [2. 4]) = 0 ۷ (0 ٨ 0) = 0 1 ⎛0 ⎜ 2 ⎜0 A3 = ⎜ 3 0 ⎜ 4 ⎜⎝1 1 1 0 1 0 0 1 1 1⎞ ⎟ 1⎟ 0⎟ ⎟ 1 ⎟⎠ Once A3 is calculated. 3] ٨ A2[3. 2] = A3 [3. 4]) = 0 ۷ (1 ٨ 1) = 1 1 ⎛0 ⎜ 2 ⎜0 A2 = ⎜ 3 0 ⎜ 4 ⎜⎝1 1 1 0 1 0 0 1 1 1⎞ ⎟ 1⎟ 0⎟ ⎟ 1⎟⎠ This matrix has only seven 0 entries. 4] = A3 [3. 1] = A3 [1. 1]) = 0 ۷ (1 ٨ 1) = 0 ۷ 1 = 1 A4[2. 2] = A3 [2.
Lecture Notes a. The spanning trees obtained using breadth first search are called Breadth first spanning trees. Then we examine all the neighbors of A.1. Both BFS and DFS impose a tree (the BFS/DFS tree) on the structure of graph. as follows: 1. Exit. 2. we can compute a spanning tree in a graph. STATUS = 3 (Processed state): The node N has been processed. They are: • Breadth first traversal (BFT) • Depth first traversal (DFT) The BFT will use a queue as an auxiliary structure to hold nodes for future processing and the DFT will use a STACK. and we need to guarantee that no node is processed more than once. During the execution of these algorithms. 6. Put the starting node A in QUEUE and change its status to the waiting state (STATUS = 2). and change their status to the waiting state (STATUS = 2). 2. Traversing a Graph Many graph algorithms require one to systematically examine the nodes and edges of a graph G. called the status of N. of Information Technology . The computed spanning tree is not a minimum spanning tree. This is accomplished by using a QUEUE to hold nodes that are waiting to be processed. Breadth first search and traversal: The general idea behind a breadth first traversal beginning at a starting node A is as follows. Add to the rear of QUEUE all the neighbors of N that are in the ready state (STATUS = 1). 199 Dept. And so on.5. Repeat the following steps until QUEUE is empty: 3. Remove the front node N of QUEUE. The spanning trees obtained using BFS are called Breadth first spanning trees. STATUS = 1 (Ready state): The initial state of the node N. STATUS = 2 (Waiting state): The node N is on the QUEUE or STACK. So.6. We need to keep track of the neighbors of a node. waiting to be processed. Initialize all nodes to the ready state (STATUS = 1). Breadth first traversal algorithm on graph G is as follows: This algorithm executes a BFT on graph G beginning at a starting node A. Process N and change the status of N to the processed state (STATUS = 3). First we examine the starting node A. There are two standard ways to do this. The spanning trees obtained using depth first search are called depth first spanning trees. 3. each node N of G will be in one of three states. Then we examine all the neighbors of neighbors of A.5. 1. and by using a field STATUS that tells us the current status of any node. b.
Exit. Process N and change the status of N to the processed state (STATUS = 3). K F A. Depth first search and traversal: Depth first search of undirected graph proceeds as follows: First we examine the starting node V. G. and change their status to the waiting state (STATUS = 2). D. C. E. Initialize all nodes to the ready state (STATUS = 1). 4. of Information Technology . J E C. Next an unvisited vertex 'W' adjacent to 'V' is selected and a depth first search from 'W' is initiated. G C A. A F C D B E J G K A Gr a p h G Node Adjacency List A F. The algorithm for depth first traversal on a graph G is as follows. Repeat the following steps until STACK is empty: a. K K E. E. When a vertex 'U' is reached such that all its adjacent vertices have been visited. G. B.2. Traverse the graph shown below in breadth first order and depth first order. C. which has an unvisited vertex 'W' adjacent to it and initiate a depth first search from W. F. b. This algorithm executes a DFT on graph G beginning at a starting node A.5. J Adjacency list for graph G Lecture Notes 200 Dept. J. This algorithm is similar to the inorder traversal of binary tree. 3. C.6. 2. Push the starting node A into STACK and change its status to the waiting state (STATUS = 2). K J D. Again field STATUS is used to tell us the current status of a node. The search terminates when no unvisited vertex can be reached from any of the visited ones. E. D G B. Pop the top node N from STACK. DFT algorithm is similar to BFT except now use a STACK instead of the QUEUE. G D C. Example 1: Consider the graph shown below. C. F. 1. B B A. D. we back up to the last vertex visited. Push all the neighbors of N that are in the ready state (STATUS = 1). E.
Depthfirst search and traversal: The steps involved in depth first traversal are as follows: Current Node Stack Processed Nodes A Status A B C D E F G J K 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 A BCF A 3 2 2 1 1 2 1 1 1 F BCD AF 3 2 2 2 1 3 1 1 1 D BCEJ AFD 3 2 2 3 2 3 1 2 1 J BCEK AFDJ 3 2 2 3 2 3 1 3 2 K BCEG AFDJK 3 2 2 3 2 3 2 3 3 G BCE AFDJKG 3 2 2 3 2 3 3 3 3 E BC AFDJKGE 3 2 2 3 3 3 3 3 3 C B AFDJKGEC 3 2 3 3 3 3 3 3 3 B EMPTY AFDJKGECB 3 3 3 3 3 3 3 3 3 For the above graph the depth first traversal sequence is: A F D J K G E C B. Lecture Notes 201 Dept. of Information Technology .Breadthfirst search and traversal: The steps involved in breadth first traversal are as follows: Current Node QUEUE Processed Nodes A Status A B C D E F G J K 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 A FCB A 3 2 2 1 1 2 1 1 1 F CBD AF 3 2 2 2 1 3 1 1 1 C BDEG AFC 3 2 3 2 2 3 2 1 1 B DEG AFCB 3 3 3 2 2 3 2 1 1 D EGJ AFCBD 3 3 3 3 2 3 2 2 1 E GJK AFCBDE 3 3 3 3 3 3 2 2 2 G JK AFCBDEG 3 3 3 3 3 3 3 2 2 J K AFCBDEGJ 3 3 3 3 3 3 3 3 2 K EMPTY AFCBDEGJK 3 3 3 3 3 3 3 3 3 For the above graph the breadth first traversal sequence is: A F C B D E G J K.
K. D. M K J L G. C H G. E. E. then the vertices of graph G are visited in the order: A F E G L J K M H I C D B.Example 2: Traverse the graph shown below in breadth first order. of Information Technology . M L. D G A. B. L. I I H J G. list J for the graph G TheM adjacency G D E F The G ra ph G If the depth first traversal is initiated from vertex A. J. The depth first spanning tree is shown in the figure given below: A F B E G L H J I K D C M Depth first Traversal If the breadth first traversal is initiated from vertex A. G B A C A. H. A B C H I J K L M Node Adjacency List A F. C. J. depth first order and construct the breadth first and depth first spanning trees. then the vertices of graph G are visited in the order: A F B C G E D L H J M I K. The breadth first spanning tree is shown in the figure given below: A F E B C D G L H J M I K Breadth first traversal Lecture Notes 202 Dept. G D E. F F A. L. F E G.
The depth first spanning tree is as follows: 1 2 4 3 5 6 7 8 Depth First Spanning Tree Lecture Notes 203 Dept. 4. 5. then the vertices of graph G are visited in the order: 1. depth first order and construct the breadth first and depth first spanning trees. of Information Technology . 2. 6. 3.Example 3: Traverse the graph shown below in breadth first order. 1 2 3 4 5 6 7 8 Graph G He ad Node s 1 2 3 2 1 4 5 3 1 6 7 4 2 8 5 2 8 6 3 8 7 3 8 8 4 5 6 7 A d j a c e n c y l is t f o r g r a p h G Depth first search and traversal: If the depth first is initiated from vertex 1. 8. 7.
7. The breadth first spanning tree is as follows: 1 2 3 4 5 6 7 8 Breadth First Spanning Tree EXCERCISES 1. 6. Write a “C” function to find out whether there is a path between any two vertices in a graph (i. Construct a weighted graph for which the minimal spanning trees produced by Kruskal’s algorithm and Prim’s algorithm are different. 6. Show that the number of vertices of odd degree in a finite graph is even.e. of Information Technology . 3. 9. 8. 2. 12. 4. 4. Lecture Notes 204 Dept. 10. Rewrite the algorithms “BFSearch” and “DFSearch” so that it works on adjacency matrix representation of graphs. 3. 5. Show that the number of spanning trees in a complete graph of “n” vertices is 2n1 – 1. then the vertices of G are visited in the order: 1. Write a “C” function to delete an existing edge from a graph represented by an adjacency list. 2. Prove that the edges explored by a breadth first or depth first traversal of a connected graph from a tree.Breadth first search and traversal: If the breadth first search is initiated from vertex 1. 7. How many edges are contained in a complete graph of “n” vertices. Explain how existence of a cycle in an undirected graph may be detected by traversing the graph in a depth first manner. Give an example of a connected directed graph so that a depth first traversal of that graph yields a forest and not a spanning tree of the graph. 8. to compute the transitive closure matrix of a graph) 11. Show that the sum of degrees of all vertices in an undirected graph is twice the number of edges. Write a “C” function to generate the incidence matrix of a graph from its adjacency matrix. 5.
c) Depth first spanning tree. For the graph given below find the following: a) Linked representation of the graph. o) Minimal spanning tree using Kruskal’s and Prim’s algorithms. l) Adjacency list. m) Depth first spanning tree. Describe the algorithm to find a minimum spanning tree T of a weighted graph G. 7 3 8 6 For the graph given below find the following: k) Linked representation of the graph. g) Adjacency list.13. j) Minimal spanning tree using Kruskal’s and Prim’s algorithms. n) Breadth first spanning tree. 5 1 6 2 4 8 3 7 Lecture Notes 205 Dept. h) Depth first spanning tree. i) Breadth first spanning tree. b) Adjacency list. Find the minimum spanning tree T of the graph shown below. 6 5 A B C 1 8 4 2 D E 3 14. 8 6 1 1 5 7 2 4 6 2 7 9 3 3 8 10 4 10 15. of Information Technology . e) Minimal spanning tree using Kruskal’s and Prim’s algorithms. d) Breadth first spanning tree. 9 5 For the graph given below find the following: f) Linked representation of the graph. 4 1 2 5 16.
For the figure 1 shown above. E) then (C. A B D C F G E D. the breadth first spanning tree visiting sequence is: A. Sibblings B. G) B. Which is the correct order for Kruskal’s minimum spanning tree algorithm to add edges to the minimum spanning tree for the figure 1 shown above: A.1 C. F) then (D. The depthfirst traversal in graph is analogous to tree traversal: A. E) then (F. D) then (E. 57 C. adjacent node C. 48 B. leaf node [ C ] 4. A B C D E F G D. A.Multiple Choice Questions 1. Complete graphs with n nodes will have__________ edges. (n – 1)/2 [ C ] 5. C) C. the depth first spanning tree visiting sequence is: A. n + 1 B. 2n [ B ] 20 A 23 C 28 36 D 25 9 E 16 3 F 7. n C. both A and B D. 68 D. G) then (B. A B C D E F G C. none of the above [ C ] 6. A B D C F G E C. Adjacency matrix C. of Information Technology . For the figure 1 shown above. D) then (D. Subgraph C. the cost of the minimal spanning tree is: A. 32 [ A ] Lecture Notes 206 B ] Dept. A graph with no cycle is called as: A. Inorder C. Acyclic graph B. Level order [ C ] 3. none of the above [ 9. C) then (A. n . none of the above [ B ] 8. All of the above [ D ] 2. n/2 D. How can the graphs be represented? A. The children of a same parent node are called as: A. D) then (D. Directed graph D. B) then (A. The maximum number of nodes at any level is: A. 2n D. nonleaf node D. Incidence matrix B. (A. A B C D E F G B. none of the above [ B ] 10. Adjacency list D. n(n1)/2 B. Preorder B. (A. Postorder D. A B C D E F G B. G) then (A. 15 4 1 Node B 17 G Adjacency List A BCD B ADE C ADF D ABCEFG E BDG F CDG G FDE FIGURE 1 and its adjacency list For the figure 1 shown above.
Which graph representation allows the most efficient determination of the existence of a particular edge in a graph? A. Incidence matrix B. An adjacency matrix. O(m) C. A shortestpath algorithm. which is a correct order for Prim’s minimum spanning tree algorithm to add edges to the minimum spanning tree? Lecture Notes 207 Dept. What is the expected number of operations needed to loop through all the edges terminating at a particular vertex given an adjacency list representation of the graph? (Assume n vertices are in the graph and m edges terminate at the desired node. O(n²) [ A ] [ B ] 19. [ D ] 13. none of the above [ B ] 15. C Level order search B. O(m²) B. B. C Level order search B. It must have at least one vertex. What graph traversal algorithm uses a queue to keep track of vertices which need to be processed? A. how many boolean values will be needed to represent G using an adjacency matrix? A. Breadthfirst search. What algorithm might be used to find the best sequence of connections from one city to another? A. What other property must a simple graph have? A. Suppose you have a directed graph representing all the flights that an airline flies. It must be undirected. C. 40 D. C. Depthfirst search. O(n) D. B. of Information Technology . starting at vertex A. O(n²) [ D ] 18. none of the above [ B ] 17. 400 [ 14.) A. Depth first search. D. O(m) C. A cyclefinding algorithm. 3 A 1 2 B 3 1 C D 5 5 4 G 4 E 6 3 D ] FIGURE 3 1 F For the figure 3. [ D ] 12.11. Breadth first search. What is the expected number of operations needed to loop through all the edges terminating at a particular vertex given an adjacency matrix representation of the graph? (Assume n vertices are in the graph and m edges terminate at the desired node. It must have no multiple edges. C.) A. D. It must be directed. D. D. Edge lists. O(m²) B. If G is an directed graph with 20 vertices. D. What graph traversal algorithm uses a stack to keep track of vertices which need to be processed? A. none of the above [ A ] 16. Breadthfirst search. O(n) D. Depthfirst search. 20 C. 200 B. A simple graph has no loops.
D) then (C. (A. (A. F) then (F. C) then (A. The set of all edges generated by DFS tree starting at node B is: A. Edges D. The set of all edges generated by BFS tree starting at node B is: A. B) then (C. E) D. (A. E) D. G) then (A. D) then (C. of Information Technology . Dijkstra’s Shortest Path Algorithm B. F) then (F. For the figure 4. C. G) then (A. B A D C G F E C. B) then (A. D) then (C. F) then (D. (A. G) then (A. Prim’s Minimum Spanning Tree Algorithm C. Direction of edges B. (A. G) then (B. Cannot be generated [ A ] 26. F) then (A. A D D. B) then (C. C) then (C. D) B. C → F [ B ] 25. C) then (C. E) then (E. B) then (B. E → C D. Which algorithm does not construct an intree as part of its processing? A. C) then (E. E) then (E. The worstcase running time of Kruskal’s minimumcost spanning tree algorithm on a graph with n vertices and m edges is: A. An adjacency matrix representation of a graph cannot contain information of: A. C) then (A. F) then (F. F) [ 21. B) then (C. B A D C G F E C. F) then (D. Cannot be generated [ C ] Lecture Notes 208 Dept. B A C D G F E B. Nodes C. C) then (E. Kruskal’s Minimum Spanning Tree Algorithm D. C → G B. C) then (A. F → E C. B) then (C. [ ] 23. which is a correct order for Kruskal’s minimum spanning tree algorithm to add edges to the minimum spanning tree? A. Parallel edges [ D ] A B Node D G F C ] Adjacency List A D B AC C GDF D  E E C CD F EA G B FIGURE 4 and its adjacency list 24. F) 20. D) then (C. F) then (F. B) then (A.A. E) C. D) B. For the figure 3. C) then (A. F) then (A. (A. G) then (G. B) then (B. D) then (A. G) then (G. (A. which edge does not occur in the depth first spanning tree resulting from depth first search starting at node B: A. A D D. B A C D G F E B. B. (A. The DepthFirst Search Trace Algorithm [ ] 22. G) then (B. D. G) then (A. E) C. D) then (A.
Chapter 7 Searching and Sorting There are basically two aspects of computer programming. it is called external sorting. Linear Search: This is the simplest of all searching techniques. There are two types of search techniques. Linear or sequential search 2. This chapter introduces this important aspect of problem solving.1. 7. After developing programming techniques to represent information. In this technique. Heap sort There are two types of sorting techniques: 1. it is logical to proceed to manipulate it. Lecture Notes 209 Dept. One is data organization also commonly called as data structures. If the desired element is found in the list then the search is successful otherwise unsuccessful. Here we study only internal sorting techniques. of Information Technology . Selection sort and 4. an ordered or unordered list will be searched one by one from the beginning until the desired element is found. The other part of computer programming involves choosing the appropriate algorithm to solve the problem. Searching is used to find the location where an element is available. External sorting If all the elements to be sorted are present in the main memory then such sorting is called internal sorting on the other hand. Internal sorting 2. 1. It is a way in which the elements are organized systematically for some purpose. Data structures and algorithms are linked each other. Bubble sort 2. Quick sort 3. Binary search Sorting allows an efficient arrangement of elements within a given data structure. if some of the elements to be sorted are kept on the secondary storage. a dictionary in which words is arranged in alphabetical order and telephone director in which the subscriber names are listed in alphabetical order. They are: 1. There are many sorting techniques out of which we study the following. Till now we have seen about data structures and the techniques and algorithms used to access them. For example.
you would need ’n’ comparisons. we’ll look at 2 elements before success 8. Determine whether element ‘x’ is present or not. we’ll look at 7 elements before success 16. 39. If it is the first element. we’ll look at 10 elements before success 9. we’ll look at 3 elements before success 54. 4. 20 If we are searching for: 45. 7. we’ll look at 8 elements before success 4. } Example 1: Suppose we have the following unsorted list: 45. If search is not successful. 9. we’ll look at 11 elements before success 20. we’ll look at 4 elements before success 77. 54. linsrch(a[n]. x) { index = 0. The time complexity of linear search is O(n). 77. we’ll look at 9 elements before success 7. if it is second element two comparisons are necessary and so on. The number of comparisons required to retrieve an element from the list. index).Suppose there are ‘n’ elements organized sequentially on a List. 16. we’ll look at 1 element before success 39. we’ll look at 5 elements before success 38 we’ll look at 6 elements before success 24. On an average you need [(n+1)/2] comparison’s to search an element. 38. } if(flag == 1) printf(“Data found at %d position“. Lecture Notes 210 Dept. one comparison will do. while (index < n) do { if (x == a[index]) { flag = 1. flag = 0. 24. 8. break. else printf(“data not found”). we’ll look at 12 elements before failure. Algorithm: Let array a[n] stores n elements. of Information Technology . purely depends on where the element is stored in the list. } index ++. we’ll look at 12 elements before success For any element not in the list.
flag = 0. i < n.h> # include <conio. printf("\n Enter the number of elements: "). &number[i]). i++) scanf("%d". i.Example 2: Let us illustrate linear search on the following 9 elements: Index Elements 0 15 1 6 2 0 3 7 4 9 5 23 6 54 7 82 8 101 Searching different elements is as follows: 1. printf("\n Enter the elements: "). Searching for x = 7 Search successful.1. data found at 3rd position. Searching for x = 42 Search unsuccessful. } 7. &n). scanf("%d".h> # include <conio.1. data. A Recursive program for linear search: # include <stdio.h> void linear_search(int a[]. i+1).2.1. data not found. 7. i++) { if(number[i] == data) { flag = 1. data found at 7th position. int data. } } if(flag == 1) printf("\n Data found at location: %d". for(i = 0. else printf("\n Data not found "). for( i = 0. of Information Technology . int n) { if(position < n) Lecture Notes 211 Dept. Searching for x = 82 Search successful. break.h> main() { int number[25]. i < n. n. clrscr(). &data). scanf("%d". printf("\n Enter the element to be Searched: "). 3. int position. 2. A nonrecursive program for Linear Search: # include <stdio.
and since an array of length ‘n’ can be halved only about log2n times before reaching a trivial length. } void main() { int a[25].{ if(a[position] == data) printf("\n Data Found at %d ". for(i = 0. linear_search(a. then further search is only necessary in that part of the file which follows a[mid]. else linear_search(a. and if so. In case ‘x’ is present. &data). if a[mid] > x. of Information Technology . If ‘x’ is not in the list then j is to set to zero (un successful search). If x < a[mid] then ‘x’ must be in that portion of the file that precedes a[mid]. i. } 7. binary search is used to find the corresponding element from the list. n). } printf("\n Enter the element to be seached: "). set j such that x = a[j] else return 0. we have to determine a value ‘j’ such that a[j] = x (successful search). clrscr(). Since the array size is roughly halved after each comparison between ‘x’ and a[mid]. data. Lecture Notes 212 Dept. n ≥ 0. Similarly. } else printf("\n Data not found"). data. Algorithm: Let array a[n] of elements in increasing order. position + 1. scanf("%d". position). data. 0. printf("\n Enter the number of elements: "). When we are given a element ‘x’. scanf("%d". where we find key a[mid]. getch(). determine whether ‘x’ is present. &a[i]). BINARY SEARCH If we have ‘n’ records which have been ordered by keys so that x1 < x2 < … < xn . n. then every unsuccessful comparison of ‘x’ with a[mid] will eliminate roughly half the unsearched portion from consideration. and compare ‘x’ with a[mid].2. If we use recursive procedure of finding the middle key a[mid] of the unsearched portion of a file. printf("\n Enter the elements: "). If x = a[mid] then the desired record has been found. In Binary search we jump into the middle of the file. &n). i < n. the worst case complexity of Binary search is about log2n. i++) { scanf("%d". n).
check 20 low = 1. check 8 low = 1. mid = 13/2 = 6. check 20. high = 12. mid = 13/2 = 6. mid = 13/2 = 6. high = 12. high = 12. check 9 low = 5. high = 5. mid = 4/2 = 2. high = 5. } return 0. high = 5. high = 2. check 20 low = 1. high = n. found Lecture Notes 213 Dept. mid = 6/2 = 3. high = 5. of Information Technology .binsrch(a[]. found If we are searching for x = 16: (This needs 4 comparisons) low = 1. high = 5. high = 5. check 4. check 4 low = 2. check 7. check 8 low = 4. mid = 13/2 = 6. } low and high are integer variables such that each time through the loop either ‘x’ is found or low is increased by at least one or high is decreased by at least one. x) { low = 1. high = 12. found If we are searching for x = 20: (This needs 1 comparison) low = 1. else return mid. mid = 6/2 = 3. check 16. Thus we have two sequences of integers approaching each other and eventually low will become greater than high causing termination in a finite number of steps if ‘x’ is not present. check 20 low = 1. check 8 low = 4. check 9. found If we are searching for x = 8: (This needs 2 comparisons) low = 1. high = 5. Example 1: Let us illustrate binary search on the following 12 elements: Index Elements 1 4 2 7 3 8 4 9 5 16 6 20 7 24 8 38 9 39 10 45 11 54 12 77 If we are searching for x = 4: (This needs 3 comparisons) low = 1. mid = 9/2 = 4. else if (x > a[mid]) low = mid + 1. high = 12. mid = 13/2 = 6. mid = 10/2 = 5. mid = 6/2 = 3. mid = 6/2 = 3. check 20 low = 1. n. high = 5. check 8. high = 12. check 8 low = 1. found If we are searching for x = 7: (This needs 4 comparisons) low = 1. high = 2. mid = 3/2 = 1. while (low < high) do { mid = ⎣ (low + high)/2 ⎦ if (x < a[mid]) high = mid – 1. found If we are searching for x = 9: (This needs 3 comparisons) low = 1. check 20 low = 1. high = 2. mid = 9/2 = 4. mid = 13/2 = 6. mid = 3/2 = 1. mid = 6/2 = 3.
mid = 15/2 = 7. 24. check 20 low = 7. found If we are searching for x = 38: (This needs 4 comparisons) low = 1. found If we are searching for x = 39: (This needs 2 comparisons) low = 1. high = 12. high = 12. mid = 19/2 = 9. 16. high = 8. check 77. check 45. mid = 22/2 = 11. high = 8. mid = 13/2 = 6. Example 2: Let us illustrate binary search on the following 9 elements: Index Elements 0 15 1 6 2 0 3 7 4 9 5 23 6 54 7 82 8 101 Solution: The number of comparisons required for searching different elements is as follows: Lecture Notes 214 Dept. check 39 low = 10. mid = 19/2 = 9. high = 12. check 39. mid = 13/2 = 6. high = 12. check 20 low = 7. high = 10. of Information Technology . check 54 low = 12. mid = 20/2 = 10. mid = 15/2 = 7. check 54. high = 12. mid = 13/2 = 6. high = 12. 4. mid = 22/2 = 11. found The number of comparisons necessary by search element: 20 – requires 1 comparison. needed to find all twelve items and dividing by 12. check 20 low = 7. mid = 24/2 = 12. high = 8. mid = 19/2 = 9. check 20 low = 7. found If we are searching for x = 54: (This needs 3 comparisons) low = 1. yielding 37/12 or approximately 3. high = 12.08 comparisons per successful search on the average. mid = 13/2 = 6. high = 12. check 20 low = 7. high = 12. found If we are searching for x = 45: (This needs 4 comparisons) low = 1. check 24. 38. high = 12. found If we are searching for x = 77: (This needs 4 comparisons) low = 1.If we are searching for x = 24: (This needs 3 comparisons) low = 1. mid = 19/2 = 9. 77 – requires 4 comparisons Summing the comparisons. high = 12. check 39 low = 7. check 24 low = 8. high = 12. mid = 19/2 = 9. check 39 low = 7. mid = 13/2 = 6. 8 and 39 – requires 2 comparisons. check 39 low = 10. high = 12. check 38. mid = 13/2 = 6. high = 12. check 20 low = 7. mid = 16/2 = 8. 9. 45. mid = 22/2 = 11. mid = 19/2 = 9. 54 – requires 3 comparisons and 7. high = 12. check 54 low = 10. check 39 low = 10. high = 12.
If we are searching for x = 101: (Number of comparisons = 4) low high mid 1 9 5 6 9 7 8 9 8 9 9 9 found 2. a(6) < x < a(7) or a(7) < x < a(8) the algorithm requires 3 element comparisons to determine that ‘x’ is not present.4 Time Complexity: The time complexity of binary search in a successful search is O(log n) and for an unsuccessful search is O(log n).77 comparisons per successful search on the average. Lecture Notes 215 Dept. yielding 25/9 or approximately 2. a(1) < x < a(2). There are ten possible ways that an unsuccessful search may terminate depending upon the value of x. Thus the average number of element comparisons for an unsuccessful search is: (3 + 3 + 3 + 4 + 4 + 3 + 3 + 3 + 4 + 4) / 10 = 34/10 = 3. Searching for x = 42: (Number of comparisons = 4) low high mid 1 9 5 6 9 7 6 6 6 7 6 not found 4. a(2) < x < a(3). a(5) < x < a(6). of Information Technology . Searching for x = 82: (Number of comparisons = 3) low high mid 1 9 5 6 9 7 8 9 8 found 3. If x < a(1). For all of the remaining possibilities BINSRCH requires 4 element comparisons. Summing the comparisons needed to find all nine items and dividing by 9. Searching for x = 14: (Number of comparisons = 3) low high mid 1 9 5 1 4 2 1 1 1 2 1 not found Continuing in this manner the number of element comparisons needed to find each of nine elements is: Index Elements Comparisons 1 15 3 2 6 2 3 0 3 4 7 4 5 9 1 6 23 3 7 54 2 8 82 3 9 101 4 No element requires more than 4 comparisons to be found.1.
high = n1.1. scanf("%d". else low = mid + 1. int data. while(low <= high) { mid = (low + high)/2.2. &data). &n). data. A recursive program for binary search: # include <stdio. i. i < n. clrscr().7.2. of Information Technology . int high) { int mid . } 7. data. break. } else { if(data < number[mid]) high = mid . if( low <= high) { mid = (low + high)/2. printf("\n Enter the elements in ascending order: "). &number[i]). n. mid + 1). mid1). low. int low.h> main() { int number[25]. printf("\n Enter the element to be searched: "). else Lecture Notes 216 Dept. scanf("%d". mid + 1). if(number[mid] == data) { flag = 1. } } if(flag == 1) printf("\n Data found at location: %d".h> void bin_search(int a[]. for(i = 0. low = 0. low.2.h> # include <conio.1. mid. if(a[mid] == data) printf("\n Element found at location: %d ". high. A nonrecursive program for binary search: # include <stdio. flag = 0. i++) scanf("%d". else printf("\n Data Not Found ").h> # include <conio. printf("\n Enter the number of elements: "). else { if(data < a[mid]) bin_search(a.
i. The process is shown below: X[0] X[1] X[2] X[3] X[4] X[5] 33 44 22 11 66 55 22 44 11 44 44 33 22 11 Remarks 44 66 55 66 55 66 The biggest number 66 is moved to (bubbled up) the right most position in the array. getch(). Bubble Sort: The bubble sort is easy to understand and program. bin_search(a. of Information Technology .e. printf("\n Enter the elements in ascending order: "). for(i = 0.bin_search(a. printf("\n Enter the element to be searched: "). high). X[i] with X[i+1] and interchange two element when they are not in proper order. } 7. mid+1. Lecture Notes 217 Dept. 0. 3. We will illustrate this sorting technique by taking a specific example. and interchange X[i] and X[i+1] if X[i] > X[i+1]. clrscr(). Then we pass through the array 5 times as described below: Pass 1: (first element is compared with all other elements). we compare each element in the file with its successor i. } else } printf("\n Element not found"). The basic idea of bubble sort is to pass through the file sequentially several times. We compare X[i] and X[i+1] for i = 0. 2. data. &n). data. i < n.. &data). } void main() { int a[25]. 1. scanf("%d". i++) scanf("%d". &a[i]). data. scanf("%d". Bubble sort is also called as exchange sort. printf("\n Enter the number of elements: "). and 4. n1). n. Example: Consider the array x[n] which is stored in memory as shown below: X[0] X[1] X[2] X[3] X[4] X[5] 33 44 22 11 66 55 Suppose we want our array to be stored in ascending order. In each pass.3.
. For an array of size n. Lecture Notes 218 Dept. but this time we leave both X[4] and X[5]. X[4]. we move the fourth biggest number 33 to X[2]. We repeat the same process. of Information Technology . We repeat the process leaving X[2]. and X[5]. We repeat the same process. By doing this. By doing this.Pass 2: (second element is compared). X[0] X[1] X[2] X[3] 22 11 33 44 11 22 22 11 Remarks 33 22 33 44 33 44 Pass 4: (fourth element is compared). and 3 and interchange X[i] and X[i+1] if X[i] > X[i+1].e. We repeat the process leaving X[3]. 2. 1. we move the third biggest number 44 to X[3]. i. X[0] X[1] X[2] 11 22 33 11 22 22 Remarks 33 Pass 5: (fifth element is compared). X[4]. X[3]. Pass 3: (third element is compared). By doing this. we compare X[i] with X[i+1] for i=0. we required (n1) passes. Thus. but this time we don’t include X[5] into our comparisons. At this time. we will have the smallest number 11 in X[0]. we see that we can sort the array of size 6 in 5 passes. and X[5]. The process is shown below: X[0] X[1] X[2] X[3] X[4] 33 22 11 44 55 22 33 11 33 33 22 Remarks 11 44 33 44 55 44 55 The second biggest number 55 is moved now to X[4]. we move the fifth biggest number 22 to X[1].
for(i = 0. scanf("%d". n.4. then it selects the next smallest element in the array x and place it at array position 1. of Information Technology . for (i = 0.h> #include <conio. j++) { if (x[j] > x[j+1]) { temp = x[j]. 7. i++) { for (j = 0. printf ("\n Array Elements after sorting: "). bubblesort(x. x[25].1. i < n. j < n–i1 .3. i < n . &x[i]). Suppose x is an array of size n stored in memory. Therefore bubble sort is very inefficient when there are more elements to sorting. printf("\n Enter the number of elements: "). Selection Sort: Selection sort will not require no more than n1 interchanges.7. } } } } main() { int i. Thus the total number of comparisons is (n1) * (n1) = n2 – 2n + 1. printf("\n Enter Data:"). } Time Complexity: The bubble sort method of sorting an array of size n requires (n1) passes and (n1) comparisons on each pass. &n). x[j+1] = temp. temp. x[i]). j. The array is passed through (n1) times and the smallest element is placed in its respective position in the array as detailed below: Lecture Notes 219 Dept. i < n. n). i++) printf ("%5d". x[j] = x[j+1]. clrscr(). i++) scanf("%d". for (i = 0. The selection sort algorithm first selects the smallest element in the array x and place it at array position 0. It simply continues this procedure until it places the biggest element in the last position of the array.h> void bubblesort(int x[]. Program for Bubble Sort: #include <stdio. which is O(n2). int n) { int i.
x[1]. . Then x[0]. x[3]. In spite of superiority of the selection sort over bubble sort and the insertion sort (there is significant decrease in run time). . . Time Complexity: In general we prefer selection sort in case where the insertion sort or the bubble sort requires exclusive swapping. x[n2] are sorted. Then x[0]. Example: Let us consider the following example with 9 elements to analyze selection Sort: 1 2 3 4 5 6 7 8 9 Remarks 65 70 75 80 50 60 55 85 45 find the first smallest element j swap a[i] & a[j] 65 find the second smallest element i 45 70 75 80 i 45 50 50 60 55 j 75 80 70 swap a[i] and a[j] 60 55 i 45 50 55 50 55 85 80 70 60 60 75 85 50 55 60 80 65 80 50 55 60 65 70 75 75 75 i 45 45 50 50 Lecture Notes 55 55 60 60 65 65 70 70 Find the fourth smallest element swap a[i] and a[j] 85 85 i 45 65 j 70 Find the third smallest element swap a[i] and a[j] i 45 65 j i 45 85 85 65 Find the fifth smallest element j swap a[i] and a[j] 70 Find the sixth smallest element j swap a[i] and a[j] 80 Find the seventh smallest element j 75 75 swap a[i] and a[j] 85 80 Find the eighth smallest element i J swap a[i] and a[j] 80 85 The outer loop ends. x[1]. . and then interchange x[j] with x[0]. x[2] are sorted.Pass 1: Find the location j of the smallest element in the array x [0]. 220 Dept. . Then x[0] is sorted. . . . during this pass x[n1] will be the biggest element and so the entire array is sorted. . Then x[0]. x[1] are sorted. x[1]. . x[2]. . Of course. . . x[n1]. Pass 3: Leave the first two elements and find the location j of the smallest element in the subarray x[2]. and then interchange x[2] with x[j]. x[n1]. . Pass 2: Leave the first element and find the location j of the smallest element in the subarray x[1]. . . its efficiency is also O(n2) for n data items. and then interchange x[j] and x[n2]. Pass (n1): Find the location j of the smaller of the elements x[n2] and x[n1]. and then interchange x[1] with x[j]. x[n1]. of Information Technology .
7. } } 7. a[i] = a[minindex]. Nonrecursive Program for selection sort: # include<stdio. n = 0. i= 0. Recursive Program for selection sort: #include <stdio. i++ ) printf( "%d ".1 ). a[minindex] = temp. minindex. int high ). i++) Lecture Notes 221 Dept. i <= high. printf( "\nEnter the elements:\n" ).h> #include<conio. 44. num .h> int x[6] = {77. selectionSort(int). int main() { int num. clrscr(). for( i=low. for (i=0. i++ ) { minindex = i. i < num. j <= high. j++ ) { if( a[j] < a[minindex] ) minindex = j. for( i=0. printf( "\nThe elements after sorting are: " ). &num). printf (" Array Elements before sorting: "). i<5. } void selectionSort( int low.h> # include<conio. &a[i] ). i< num. j=0. clrscr(). a[i] ).4.1. i++) scanf( "%d". 66}. main() { int i. printf( "Enter the number of elements: " ). } temp = a[i]. return 0. temp=0. for( j=i+1. selectionSort( 0. scanf("%d". 11.h> void selectionSort( int low.2. for(i=0. 33.4. int a[25]. of Information Technology . int high ) { int i=0.
When all the subsets have been partitioned and rearranged. p = n. Once the array has been rearranged in this way with respect to the pivot. 3. C.5. selectionSort(n). of Information Technology . the original array is sorted. p = k. min = x[n]. The chosen value is known as the pivot element. Hoare in the early 1960’s. interchange a[down] with a[up] 4. The quick sort algorithm partitions the original array by rearranging it into two groups. Lecture Notes 222 Dept. /* call selection sort */ printf ("\n Array Elements after sorting: "). for (i=0. If ‘up’ pointer crosses ‘down’ pointer. 2. Quick Sort: The quick sort was invented by Prof. n++ . A. Repeatedly increase the pointer ‘up’ until a[up] >= pivot. if (n== 4) return (1). The first group contains those elements less than some arbitrary chosen value taken from the set. x[p] = temp. It was one of the first most efficient sorting algorithms. It is an example of a class of algorithms that work by “divide and conquer” technique. If down > up. i<5. } selectionSort( int n) { int k. for (k = n+1. } 7. selectionSort(n). x[i]). Repeatedly decrease the pointer ‘down’ until a[down] <= pivot. 2 and 3 till the ‘up’ pointer crosses the ‘down’ pointer. k<5. k++) { if (x[k] <min) { min = x[k]. the position for pivot is found and place pivot element in ‘down’ pointer position. and the second group contains those elements greater than or equal to the chosen value. min. i++) printf ("%d ". the same partitioning procedure is recursively applied to each of the two subsets. x[i]). p. } } temp = x[n]. The function partition() makes use of two pointers up and down which are moved toward each other in the following fashion: 1. temp. Repeat the steps 1.printf ("%d ". R. /* interchange x[n] and x[p] */ x[n] = x[p].
p) { v = a[m]. // j is the position of the partitioning element // a[m] is the partition element repeat down = down – 1. . pivot = x[low]. x[j+2]. Here we choose the first element as the ‘pivot’. . q) { if ( p < q ) then { call j = PARTITION(a. 2. Algorithm Sorts the elements a[p]. } Lecture Notes 223 Dept. until (a[up] > v). . . call quicksort(j + 1 . The time complexity of quick sort algorithm is of O(n log n). . until (a[down] < v).e. if (up < down) then call interchange(a. The algorithm of quick sort function sorts all elements in an array ‘a’ between positions ‘low’ and ‘high’. up. 1.The program uses a recursive function quicksort(). return (down). . x[j1] and x[j+1]. . So. x[j1] between positions low and j1 (where j is returned by the partition function). down = p. pivot. . } while (up > down). . q+1). . } } partition(a. . a[down] = v. a[n + 1] = + ∝ quicksort (p. . . . x[j+2]. x[low+1]. down). p. . It calls itself recursively to sort the right subarray x[j+1]. . . . . 4. 3. do { repeat up = up + 1. call quicksort(p. q). . x[high]. x[low+1]. It terminates when the condition low >= high is satisfied. j – 1). x[high] between positions j+1 and high. . It calls itself recursively to sort the left subarray x[low].a[q] which reside in the global array a[n] into ascending order. The a[n + 1] is considered to be defined and must be greater than all elements in a[n]. Then we will have two subarrays x[low]. Now it calls the partition function to find the proper position j of the element x[low] i. This condition will be satisfied only when the array is completely sorted. . . m. up = m. . of Information Technology . a[m] = a[down].
} Example: Select first element as the pivot element. This process continues till the ‘up’ pointer crosses the ‘down’ pointer. down) { p = a[up]. Let us consider the following example with 13 elements to analyze quick sort: 1 2 3 4 5 6 7 8 9 10 11 12 13 38 08 16 06 79 57 24 56 02 58 04 70 45 pivot up down pivot 04 79 pivot up down pivot 02 57 pivot (24 08 16 06 04 pivot (02 pivot. up. Move ‘up’ pointer from left to right in search of an element larger than pivot. down. the elements are swapped. a[up] = a[down]. up (02 04 Lecture Notes 06 08 16 24) 38 224 Dept.interchange(a. the position for pivot is found and interchange pivot and element at ‘down’ position. a[down] = p. If such elements are found. up 16 pivot. down. of Information Technology . down 02 08 16 06 04) down up 02) 38 (56 down up swap up & down swap pivot & down 57 58 79 70 45) 24 swap pivot & down (08 16 pivot up pivot 04 pivot 04) pivot down (04) swap up & down swap pivot & down up (06 Remarks 06 04) swap up & down down 16 down Up 08 (16) swap pivot & down up swap pivot & down 06 04 pivot. Move the ‘down’ pointer from right to left in search of an element smaller than pivot. If ‘up’ pointer crosses ‘down’ pointer.
int partition(int. void interchange(int. down.1. printf( "\nThe elements after sorting are: " ). int array[25]. i++) scanf( "%d". up up swap pivot & down 79 pivot. down.h> void quicksort(int. i = 0. &num). down 70 79) swap pivot & down 57 pivot. printf( "Enter the elements: " ). up (58 56 79 70 45) swap up & down swap pivot & down 79 70 57) swap pivot & down (58 pivot (57) 79 up 57 70 57) swap up & down down 79 down up 58 (70 79) (70 pivot. down. printf( "Enter the number of elements: " ). int main() { int num. int). int). quicksort(0. num 1).h> # include<conio. int). scanf( "%d". clrscr(). of Information Technology .5. Lecture Notes 225 Dept.(56 57 58 pivot up down pivot 45 57 pivot down up (45) 45 pivot. i < num. 06 08 16 24 38 (45 56 57 58 70 79) 45 56 57 58 70 79 Recursive program for Quick Sort: # include<stdio. &array[i] ). for(i=0. up 02 04 7.
array[i] = array[j]. } } int partition(int low. int high) { int pivot = array[low]. i++) printf("%d ". array[j] = temp. return 0. i < num. down). do down = down . int high) { int pivotpos. } Lecture Notes 226 Dept.1). quicksort(low. array[low] = array[down]. int up = low. temp = array[i]. array[down] = pivot. while(array[up] < pivot ).1. high + 1). do { do up = up + 1. void interchange(int i. pivotpos . return down. if(up < down) interchange(up. high). } } while(up < down). array[i]). } void quicksort(int low. down = high. quicksort(pivotpos + 1. of Information Technology .for(i=0. if( low < high ) { pivotpos = partition(low. int j) { int temp. while(array[down] > pivot).
7. A heap tree represented using a single array looks as follows: X[1] X[2] X[3] X[4] X[5] X[6] X[7] X[8] 65 45 60 40 25 50 55 30 x[ 1] x[ 2] x[ 4] x[ 8] Lecture Notes 30 65 x[ 3] 60 45 x[ 7] x[ 6] 40 x[ 5] 2 5 50 55 He a p T r e e 227 Dept. a heap tree can be efficiently represented using one dimensional array. • The parent of an element stored at location i can be found at location floor(i/2). which provides these two operations. • The right child of an element stored at location i can be found in location 2*i+1. of Information Technology . The elements of the array can be thought of as lying in a tree structure.6. A data structure. • The left child of an element stored at location i can be found in location 2*i. is called a priority queue. Max and Min Heap data structures: A max heap is an almost complete binary tree such that the value of each node is greater than or equal to those in its children. Heap and Heap Sort: Heap is a data structure. • The root of the tree is in location 1. Representation of Heap Tree: Since heap is a complete binary tree. This provides a very convenient way of figuring out where children belong to.2. which permits one to insert elements into a set and also to find the largest element efficiently. 7.6.6. 95 15 85 75 55 45 25 65 45 35 15 55 85 Max heap 25 65 35 75 Min heap 95 A min heap is an almost complete binary tree such that the value of each node is less than or equal to those in its children.1. 7. Priority Queue.
of Information Technology . Now. 90 will be added as left child of 40. parent’s value greater than child’s value is satisfied. // move the parent down i = ⎣ i/2 ⎦ . i = n. when 90 is compared with 40 it requires interchange. 45. n) { //inserts the value in a[n] into the heap which is stored at a[1] to a[n1] int i. hence interchange as well as further comparisons are no more required.3. Merging. our process stops here. 1. The path on which these comparisons and interchanges have taken places are shown by dashed line. Next. As another illustration. Its value is compared with its parent’s value. Insertion into a heap tree: This operation is used to insert a node into an existing heap tree satisfying the properties of heap tree. 90 is compared with 80. 35. This will continue between two nodes on path from the newly inserted node to the root node till we get a parent whose value is greater than its child or we reached the root. 2. Operations on heap tree: The major operations required to be performed on a heap tree: 1. 70. For illustration. } Example: Form a heap using the above algorithm for the data: 40. 90. Insertion. The principle of insertion is that.7. item = a[n]. The algorithm Max_heap_insert to insert a data into a max heap tree is as follows: Max_heap_insert (a.6. Using repeated insertions of data. Next. we have to compare it with the data in its parent. first we have to adjoin the data in the complete binary tree. starting from an empty heap tree. another interchange takes place. let us consider the case of insertion 90 into the resultant heap tree. and to be a max heap. n. Insert 40: 40 Lecture Notes 228 Dept. return true . 80. one can build up a heap tree. 50. 35 is added as the right child of 80. First. if the value is greater than that at parent then interchange the values. } a[i] = item . Let us consider the heap (max) tree. while ( (i > 1) and (a[ ⎣ i/2 ⎦ ] < item ) do { a[i] = a[ ⎣ i/2 ⎦ ] . Deletion and 3. as 90 is now in root node.
Insert 80: 80 40 40 80 80 3.2. 90 50 35 50 45 80 50 35 40 45 35 Insert 70: 90 90 70 80 50 70 80 50 40 Lecture Notes 45 35 70 40 229 45 35 50 Dept. 40 Insert 35: 80 40 4. 35 Insert 90: 90 80 80 90 90 40 35 80 35 40 40 90 5. 35 45 Insert 50: 90 80 40 7. Insert 45: 90 80 40 6. of Information Technology .
n. Then reheap the tree as stated below: • Let newly modified root node be the current node. ITEM. n1). return true. they are interchanged. So. } adjust (a. 99 is replaced by 26 and this node with data 26 is removed from the tree. The principle of deletion is as follows: • Read the root node into a temporary storage say. 1 < i < n. // a position for item is found else a[ ⎣ j / 2 ⎦ ] = a[j] // move the larger child up a level j = 2 * j. Now. • Make X as the current node. No node has an address greater than n or less than 1. } a [ ⎣ j / 2 ⎦ ] = item. i. while (j < n) do { if ((j < n) and (a (j) < a (j + 1)) then j Å j + 1. Lecture Notes 230 Dept. if the current node is not an empty node. n) // The complete binary trees with roots a(2*i) and a(2*i + 1) are combined with a(i) to form a single heap. • Replace the root node by the last node in the heap tree. Interchange the value of X with the value of the current node. x) // delete the maximum from the heap a[n] and store it in x { if (n = 0) then { write (“heap is empty”).Deletion of a node from heap tree: Any node can be deleted from a heap tree. The algorithm for the above is as follows: delmax (a. adjust (a. } x = a[1]. Compare its value with the value of its two child. 1. Let X be the child whose value is the largest. } Here the root node is 99. The last node is 26. As 63 is greater. of Information Technology . item = a[i] . • Continue reheap. return false. But from the application point of view. it is in the level 3. deleting the root node has some special importance. // compare left and right child and let j be the larger child if (item > a (j)) then break. Next 26 at root node is compared with its two child 45 and 63. // { j = 2 *i . a[1] = a[n].
6.4. 2. 26 63 99 26 45 63 57 63 45 57 26 35 27 29 12 24 57 42 35 26 27 De l e t i n g t h e n o d e w it h d at a 9 9 7. Merging operation consists of two steps: Continue steps 1 and 2 while H2 is not empty: 1. 92 59 45 13 92 19 Resultant max heap after merging H1 and H2 Application of heap tree: They are two main applications of heap trees known are: 1. say x.6. hence reheap is completed. 57 and 42. namely. Now. Sorting (Heap sort) and 2. Merging the tree H2 with H1 means to include all the node from H2 to H1. 29 12 26 42 24 Af t er De l e t i o n of n o d e w it h d at a 9 9 Merging two heap trees: Consider. Reheap H2. from H2. of Information Technology . 26 appears as the leave node. H2 may be min heap or max heap and the resultant tree will be min heap if H1 is min heap else it will be max heap. Priority queue implementation. as 57 is greater. two heap trees H1 and H2. 92 13 59 38 67 19 45 92 H1: max heap 80 93 96 H2: min heap + 96 93 67 80 38 7. Lecture Notes 231 Dept. Insert the node x into H1 satisfying the property of H1.5. Delete the root node.26 is compared with its children. so they are interchanged.
} Lecture Notes 232 Dept. Algorithm: This algorithm sorts the elements a[n]. Remove the top most item (the largest) and replace it with the last element in the heap. } adjust (a. i – 1). 1 < i < n. while (j < n) do { if ((j < n) and (a (j) < a (j + 1)) then j Å j + 1. Any kind of data can be sorted either in ascending order or in descending order using heap tree. adjust (a. n) //Readjust the elements in a[n] to form a heap. // compare left and right child and let j be the larger child if (item > a (j)) then break. n) { heapify(a. a[1] = temp. 1. Reheapify the complete binary tree. It does this with the following steps: 1. Heap sort rearranges them inplace in nondecreasing order. a[i] = a[1]. i. b. { for i Å ⎣ n/2 ⎦ to 1 by – 1 do adjust (a. // a position for item is found else a[ ⎣ j / 2 ⎦ ] = a[j] // move the larger child up a level j = 2 * j. Place the deleted node in the output. // { j = 2 *i . a.7. No node has an address greater than n or less than 1. 3. heapsort(a. 2. item = a[i] . } } heapify (a. Continue step 2 until the heap tree is empty. n). n). HEAP SORT: A heap sort algorithm works by first organizing the data to be sorted into a special type of binary tree called a heap. i. n) // The complete binary trees with roots a(2*i) and a(2*i + 1) are combined with a(i) to form a single heap. for i = n to 2 by – 1 do { temp = a[i]. } a [ ⎣ j / 2 ⎦ ] = item.7. First transform the elements into a heap. of Information Technology . c. Build a heap tree with the given set of data.
35. where ‘k’ is the number of elements in the heap at the time. of Information Technology . Example 1: Form a heap from the set of elements (40. 90. Since we always have k ≤ n. Solution: First form a heap tree from the given set of data and then sort by repeated deletion operation: 40 40 80 35 90 45 80 50 70 90 70 45 90 70 45 35 40 40 80 50 50 70 90 35 80 45 50 35 90 70 80 40 Lecture Notes 45 50 35 233 Dept. where ‘k’ is the number of elements in the heap at the time. 80. so the priority queue sorting algorithm runs in O(n log n) time when we use a heap to implement the priority queue. each such operation runs in O(log n) time in the worst case. Thus. Likewise. 70) and sort the data using heap sort. each of the ‘n’ remove operations also runs in time O(log k). for ‘n’ elements it takes O(n log n) time.Time Complexity: Each ‘n’ insertion operations takes O(log k). 50. 45.
of Information Technology . 45 70 80 35 90 50 45 70 80 90 Exchange root 40 with the last element 35 of the array and reheapify 35 40 50 45 70 80 90 The sorted tree Lecture Notes 234 Dept. Exchange root 80 with the last element 50 of the array and reheapify 70 70 50 45 40 3.1. 35 80 50 45 40 90 50 35 80 Exchange root 70 with the last element 35 of the array and reheapify 50 35 50 35 45 50 45 40 4. 35 70 80 40 90 50 35 70 80 90 Exchange root 45 with the last element 35 of the array and reheapify 40 35 40 35 40 50 6. 70 70 80 90 40 70 90 35 80 90 Exchange root 50 with the last element 40 of the array and reheapify 45 40 45 40 45 50 5. Exchange root 90 with the last element 35 of the array and reheapify 80 35 80 45 35 80 70 40 45 45 50 90 40 70 35 50 90 35 2.
while(j <= n) { if((j < n) && (a[j] < a[j+1])) j++. for(i = n/2. i<=n. } } a[j/2] = item. i > 0. adjust(1. for (i=1. j = 2 * i. i++) printf("%5d". item.1. } void heapsort(int n. scanf("%d". int a[]) { int i. n. &n).1. n).int a[]) { int temp. i++) scanf("%d". of Information Technology . a). j = 2*j. Program for Heap Sort: void adjust(int i. for (i=1. a[i]). int a[]) { int j. n. } Lecture Notes 235 Dept. } void heapify(int n. else { a[j/2] = a[j]. if(item >= a[j]) break. a). printf("Enter %d elements: ". a). i) adjust(i. clrscr(). getch(). a). i) { temp = a[i]. item = a[i]. i<=n. int n. a[1] = temp. } } void main() { int i.7. heapsort(n. printf("\n How many element you want: "). i . &a[i]). a[20].7. heapify(n. i > 0. printf("\n The sorted elements are: \n"). i. a[i] = a[1]. for(i = n.
0. The several elements of this array may contain the same number “x”. 1. 9. Elements associated with their priority values are to be stored in from of heap tree. which can be formed based on their priority values. the heap. 6. 7. The order of servicing the process is successive deletion of roots from the heap. Exercises 1. 13. When a “C” function to sort a matrix rowwise and columnwise.7. 11. The top priority element that has to be processed first is at the root. 3. Here is an array of ten integers: 5 3 8 9 1 7 0 2 6 4 Suppose we partition this array using quicksort's partition function and using 5 for the pivot. Find the expected number of passes. 8. 9. 2. 3. 12. 8. 6. 9. 8. 4. Show the result of inserting 10. Write an algorithm to find the total number of elements which are equal to “x” and also indicate the position of the first such element in the array. 6. Which of these elements could be the pivot? (There may be more than one possibility!) 8. 3. Lecture Notes 236 Dept. The program is to be run on a personal computer with limited memory. Write a recursive “C” function to implement binary search and compute its time complexity.8. An array contains “n” elements of numbers. Assume that a process having higher priority value will be serviced first. 9. As an illustration. 1. 5. Priority queue implementation using heap tree: Priority queue can be implemented using circular array. 4. 9. and so on. 15. 5. one at a time. 5. 4. As heap trees allow the duplicity of data in it. 2. 2. 7. however. 7. 10. 4. The heap tree can be formed considering the process priority values. Assume that the matrix is represented by a two dimensional array. 5. A very large array of elements is to be sorted. and 2. consider the following processes with their priorities: Process P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 Priority 5 4 3 4 5 5 3 2 1 5 These processes enter the system in the order as listed above at time 0. Another simplified implementation is possible using heap tree. can be represented using an array. 5. Compare these results with the actual number of operations when the given sequence is as follows: 7. of Information Technology . into an initially empty binary heap. 1. 14. so it can be deleted and heap can be rebuilt to get the next element to be processed. This implementation is therefore free from the complexities of circular array and linked list but getting the advantages of simplicities of array. Sort the sequence 3. say. Draw the resulting array after the partition finishes. 5 using insertion sort. 6. Here is an array which has just been partitioned by the first step of quicksort: 3. Which sort would be a better choice: Heap sort or Quick sort? Why? 6. 2. 4. comparisons and exchanges for bubble sort when the number of elements is equal to “10”. linked list etc.
When is insertion sort a good choice for sorting an array? A. 5 using quick sort with medianofthree partitioning and a cutoff of 3. Which searching can be performed iteratively ? A. 572. Which searching can be performed recursively ? A. The array's size must be a power of two. 11. What is the worstcase time for serial search finding a single item in an array? A. 879. 6. 3. 21 C. Sort 3. 1. Suppose that a selection sort of 100 items has completed 42 iterations of the main loop. O(n log n) sorts C. Constant time C. Binary search B. Quadratic time D. Divideandconquer sorts B. B. 5. The array must have at least 2 entries C.1 A. 43 [ C ] 9. linear search C. 2. D. 111. Quadratic time D. In a selection sort of n elements. 434. The processor speed is fast [ B ] Lecture Notes 237 B ] Dept. linear search C. Interchange sorts D. Multiple Choice Questions 1. 9. so that binary search may be used to locate an entry? A. n log n B. The array must be sorted. Each component of the array requires a small amount of memory D. Linear time [ B ] 3. 811. 242. Average time is quadratic [ B ] 8. Each component of the array requires a large amount of memory B. How many items are now guaranteed to be in their final spot (never to be moved again)? A. Show how heap sort processes the input 142. Logarithmic time B. n . Linear time [ D ] 2. What additional requirement is placed on an array. The array elements must form a heap.10. 1 D. Binary search B. 42 B. Constant time C. both D. 123. Logarithmic time B. none [ B ] 6. none [ 5. of Information Technology . 4. n2 [ B ] 7. What is this category? A. 453. how many times is the swap function called in the complete execution of the algorithm? C. What is the worstcase time for binary search finding a single item in an array? A. both D. [ C ] 4. 1. 41 D. The array has only a few items out of place C. 543. Selection sort and quick sort both fall into the same category of sorting algorithms. 102. 65. 5.
first element of list C. a desirable choice for the portioning element will be A. bubble sort [ D ] 18. leaf C. O(n) A. O(n²) [ 13. both D. Binary search B. What is the worstcase time for heap sort to sort an array of n elements? A. n2 D. of Information Technology . O(log n) C. C. A. In the quick sort method . The pivot is not the 7. any element of list [C ] 17. O(n) D. any where [B ] 16. Running time of Heap sort algorithm is . backtrack B. 2 B. intermediate parent B. 3 or 4 D. O(n log n) B. O( n log2 n) D. Divide and conqueror C. and we have just finished one of the reheapifications downward. C. 1 C. D. The pivot could be the 7. Bubble sort [ C ] 20. What is the worstcase time for quick sort to sort an array of n elements? A. merge sort B. root D. Quick sort is also known as A. Linear search C. n [ A ] 15. last element of list D. A. Neither the 7 nor the 9 is the pivot [ A ] 12. greedy D. The pivot could be either the 7 or the 9. but it is not the 9. log2 n B. and we have just finished the first partitioning with the array looking like this: 2 5 1 7 9 12 11 10 Which statement is correct? A. Which among the following is fastest sorting technique (for unordered data) A. Suppose we are sorting an array of eight integers using heap sort. Which design algorithm technique is used for quick sort . The array now looks like this: 6 4 5 1 2 7 8 How many reheapifications downward have been performed so far? A.10. heap sort D. O(log n) C. none [ C ] 21. B. O(n) D. O(n2) [ B ] Lecture Notes C. but it could be the 9. O( log2 n) B. O(n log n) B. 5 or 6 [B ] 14. dynamic programming [ A ] 19. Suppose we are sorting an array of eight integers using quick sort. Heap sort C. O(n²) [D ] 11. Quick Sort B. In which searching technique elements are eliminated by half in each pass . n log2n A. Selection Sort D. none 238 C ] Dept. median of list B. A. Time complexity of inserting an element to a heap of n elements is of the order of C. A min heap is the tree structure where smallest element is available at the A.
60.60. The Max heap constructed from the list of numbers 30.22. O( n log2 n) D. O( log2 n) C. The number of swappings needed to sort the numbers 8.60. O( log2 n) C.31.80.60.10. Binary search algorithm performs efficiently on a A.19. 13 B. linear queue B. A. O( n log2 n) D. Bubble sort B. array B. O(n) A. O(n2) [ C ] 27.55.15 C. A. 12 D.15.55. O( log2 n) B. none [ 25. 80. O(n2) [D ] 24.10.5. A. none 239 ] Dept. Always Heap is a A.10. Running time of Bubble sort algorithm is . priority Queue C. Time complexity of insertion sort algorithm in best case is C.10. Binary Search Tree [ Lecture Notes C. complete Binary tree B. Quick sort D.30 B.15. Heap is a good data structure to implement A. Which is a stable sort ? A. linked list C.30.30.15 D. O( n log2 n) D. A. O(n2) [ D ] 23. 80. none [ A 30. none [C ] 28. O(n) B. of Information Technology .9. A.7. Full Binary tree D.13 in ascending order using bubble sort is A. O(n) B. Selection Sort [ 29.55.22.55 is A. both D. Deque D. Running time of Selection sort algorithm is . 14 [ D ] 26. none C ] D ] A ] C.80. 11 C.
This action might not be possible to undo. Are you sure you want to continue?
Use one of your book credits to continue reading from where you left off, or restart the preview.