You are on page 1of 68

II B.

Tech

Data Stractures

INDEX
S.No

PROGRAMS LIST
1 Write recursive program which computes the nth Fibonacci number, for appropriate values of n. Analyze behavior of the program Obtain the frequency count of the statement for various values of n. Write recursive program for the following a) Write recursive C program for calculation of Factorial of an integer b) Write recursive C program for calculation of GCD (n, m) c) Write recursive C program for Towers of Hanoi : N disks are to be transferred from peg S to peg D with Peg I as the intermediate peg. a) Write C programs that use both recursive and non recursive functions to perform Linear search for a Key value in a given list. b) Write C programs that use both recursive and non recursive functions to perform Binary search for a Key value in a given list. c) Write C programs that use both recursive and non recursive functions to perform Fibonacci search for a Key value in a given list. a) Write C programs that implement Bubble sort, to sort a given list of integers in ascending order b) Write C programs that implement Quick sort, to sort a given list of integers in ascending order c) Write C programs that implement Insertion sort, to sort a given list of integers in ascending order a) Write C programs that implement Heap sort, to sort a given list of integers in ascending order b) Write C programs that implement Radix sort, to sort a given list of integers in ascending order c) Write C programs that implement Merge sort, to sort a given list of integers in ascending order a) Write C programs that implement stack (its operations) using arrays b) Write C programs that implement stack (its operations) using Linked list a) Write a C program that uses Stack operations to Convert infix expression into postfix expression b) Write C programs that implement Queue (its operations) using arrays. c) Write C programs that implement Queue (its operations) using linked lists a) Write a C program that uses functions to create a singly linked list b) Write a C program that uses functions to perform insertion operation on a singly linked list c) Write a C program that uses functions to perform deletion operation on Page |1 Department of Computer Science & Engineering

Page no

3

2

4 5 7 11 12 13 15 15 16 18 22 25 27 30 34 36 39
45

3

4

5

6 7

8

48 50 GEC

II B.Tech

Data Stractures

9

a singly linked list d) Adding two large integers which are represented in linked list fashion. e) Write a C program to reverse elements of a single linked list. f) Write a C program to store a polynomial expression in memory using linked list g) Write a C program to representation the given Sparse matrix using arrays. a) Write a C program to Create a Binary Tree of integers
b) Write a recursive C program, for Traversing a binary tree in preorder, in order and post order.

53 54 55 57
59 61

10

11

12

a) Write a C program to Create a BST b) Write a C program to insert a note into a BST. c) Write a C program to delete a note from a BST. a) Write a C program to compute the shortest path of a graph using Dijkstra’s algorithm b) Write a C program to find the minimum spanning tree using Warshall’s Algorithm ADD ON PROGRAMS : Write a C program on Circular Queue operations Write a C program on Evaluation on Postfix Expression
Write a C program search the elements using Breadth First Search Algorithm & Depth First Search Algorithm Write a C program to perform various operations i.e., insertions and deletions on AVL trees.

63 65 66 67 69

1 2 3 4

105 107 108 111

Page |2

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Exercise 1:
Write recursive program which computes the nth Fibonacci number, for appropriate values of n. Analyze behavior of the program Obtain the frequency count of the statement for various values of n. DESCRIPTION: C Programming Language: Using Recursion to Print the Fibonacci Series? The Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, ….. Begins with the terms 0 and 1 and has the property that each succeeding term is the sum of the two preceding terms. For this problem, we are asked to write a recursive function fib (n) that calculates the nth Fibonacci number. Recursion MUST be used. In an earlier problem, we where asked to do the exact same thing, except we where to NOT use recursion. For that problem, I used the following code (between the dotted lines):

ALGORITHM :
1. Start. 2. Get the number n up to which Fibonacci series is generated. 3.Call to the function fib.

Page |3

Department of Computer Science & Engineering

GEC

II B. Stop.stop Algorithm fib 1. Page |4 Department of Computer Science & Engineering GEC .if n=0 or 1 then return n 3.else return fib(n-1)+fib(n-2) 4.Tech Data Stractures 4.start 2.

let us define a procedure for counting the factorial of a number. The procedure trace shows the intermediate steps as the recursion proceeds as well as the intermediate values returned. recursive procedures need a terminating condition (otherwise they will run forever) and a recursive step (describing how the computation should proceed). We are now ready to define the procedure itself: (define fact (lambda (n) (if (= n 0) . In general. the terminating condition 1 .II B. Write recursive C program for calculation of Factorial of an integer Recursion : Procedures which call themselves within the body of their lambda expression are said to be recursive.n 1)))))) . returning 1 (* n (fact (. which gives us our recursive step. the recursive step Let' see what happens if we try to compute the factorial of 7 by using the procedure trace: > (fact 7) 5040 > (trace fact) (fact) > (fact 7) |(fact 7) | (fact 6) | |(fact 5) | | (fact 4) | | |(fact 3) | | | (fact 2) | | | |(fact 1) | | | | (fact 0) ||||1 | | |6 | | 24 | |120 | 720 |5040 5040 > (untrace fact) (fact) Page |5 Department of Computer Science & Engineering GEC . Apart from that. We know that equals 1 and we will use this as our terminating condition. We will use one of MzScheme's procedures trace to illustrate the behavior of recursive procedures. we know that is the same as .Tech Data Stractures Exercise 2: a). For example.

Call to the function fact. 4. 2.Tech Data Stractures ALGORITHM : 1.Start 2. 3.Else return n*fact(n-1) 4. Start. Get the number n to which Fcatorial value is to be generated.Stop Page |6 Department of Computer Science & Engineering GEC .II B.Stop Algorithm fact 1.if n=0 or 1 then return 1 3.

Note that when a zero remainder occurs.B9) 10 =B9 =C9 =MOD (A10.B6) 7 =B6 =C6 =MOD (A7.B8) 9 =B8 =C8 =MOD (A9. m) ALGORITHM : The GCD algorithm: Given m. We continue replacing a by the divisor and b by the remainder until we get a remainder 0.n) We proved in class that the gcd can be found by repeatedly applying the division algorithm: a = bq + r.B7) 8 =B7 =C7 =MOD (A8. Write recursive C program for calculation of GCD (n. the spreadsheet gives an error message on the following line. The spreadsheet automatically updates the formulas (that is what spreadsheets do!). it is copied to all lower rows. Page |7 Department of Computer Science & Engineering GEC .B5) 6 =B5 =C5 =MOD (A6.B11) 12 =B11 =C11 =MOD (A12.B13) 14 =B13 =C13 =MOD (A14.B4) 5 =B4 =C4 =MOD (A5.B12) 13 =B12 =C12 =MOD (A13.Tech Data Stractures b). The last non-zero remainder is the gcd.r) [the quotient is not needed here].n find gcd(m. A new pair of numbers can be entered in A2 and B2.B14) Once row 5 is entered. The next pair is (b.B10) 11 =B10 =C10 =MOD (A11. b=n.II B. This algorithm can be performed on a spreadsheet: ABC 1 mn 2 123456 654321 3 abr 4 123456 654321 123456 5 654321 123456 37041 6 123456 37041 12333 7 37041 12333 42 8 12333 42 27 9 42 27 15 10 27 15 12 11 15 12 3 12 12 3 0 13 3 0 #DIV/0! 14 0 #DIV/0! #DIV/0! ABC 1 mn 2 123456 3 654321 4 =A2 =B2 =MOD (A4. We start with a=m.

at start.II B. 3 Solving the Tower of Hanoi Page |8 Department of Computer Science & Engineering GEC . 2 The Arbitrary Towers of Hanoi . At the end. 3). Fig. 1 The solution of the puzzle is to build the tower on post 'C'.Tech Data Stractures c). DESCRIPTION: How to solve the Towers of Hanoi puzzle The Classical Towers of Hanoi . disks can be in any position provided that a bigger disk is never on top of the smaller one (see Fig. disks should be in another arbitrary position. Write recursive C program for Towers of Hanoi: N disks are to be transferred from peg S to peg D with Peg I as the intermediate peg. * ) Fig.an initial position of all disks is on post 'A'. Fig.

we need disk 3 in place where it is now. To obtain that.'regular' to 'perfect' Let's start thinking how to solve it.. Disk 4 is on peg 'A' and the 3 disk-high tower is on peg 'B' and target peg 'C' is empty. So think back. If moveable to goal peg Then move Else 3. 2). Solving the Tower of Hanoi . 4 From that position we have to move disk 4 from 'A' to 'C' and move by some magic the 3 disk-high tower from 'B' to 'C'. Fig. Then on the way of solving there is one special setup. 4. Identify biggest discrepancy (=disk N) 2. assume that our goal is to set a 4 disk-high tower on peg 'C' . for the sake of clarity. Subgoal: set-up (N−1)-disk tower on non-goal peg. We need disk 3 on peg 'B'. Let's. .Tech Data Stractures 'Solution' ≡ shortest path Recursive Solution: 1. Let's assume we 'know' how to move a 'perfect' 3 disk-high tower.just like in the classical Towers of Hanoi (see Fig.II B. free peg 'B' and disks 2 and 1 stacked on peg 'A'. So our goal now is to put disk 2 on Page |9 Department of Computer Science & Engineering GEC .. Go to 1. Forget the disks bigger than 3. Disk 3 is on peg 'C'.

Fig.II B. disks smaller than disk 2 stacked on peg 'B'. To be able to put disk 2 on peg 'A' we need to empty peg 'A' (above the thin blue line). 5 Forget for the moment disk 3 (see Fig.Tech Data Stractures peg 'A'. Fig. So. 6). 7 The steps above are made by the algorithm implemented in Towers of Hanoi when one clicks the "Help me" button. this is an easy task because disk 1 has no disk above it and peg 'B' is free. This button-function makes analysis of the current position and generates only one single move which leads to the solution. our goal now is to put disk 1 on peg 'B'. the algorithm repeats all steps of the analysis starting from the position of the biggest disk . Fig. As we can see. 6 So let's move it. When the 'Help me' button is clicked again.in this example disk 4 . It is by design.and generates the P a g e | 10 Department of Computer Science & Engineering GEC .

that is to remember previous steps of the analysis and not to repeat the analysis of the Towers from the ground.II B.disk 2 from peg 'C' to peg 'A'. P a g e | 11 Department of Computer Science & Engineering GEC . /*A recu rsiv e c prog ram for towe rs of hano i: N disk s are to be Fig. 8 If one needs a recursive or iterative algorithm which generates the series of moves for solving arbitrary Towers of Hanoi then one should use a kind of back track programming.Tech Data Stractures next move .

We begin by examining the middle element of the array.Tech Data Stractures Exercise 3: a). ALGORITHM : Linear Search ( ): Description: Here A is an array having N elements. we would need to shift A[3]…A[6] down by one slot. Therefore it takes only three iterations to find any number. ITEM is the value to be searched.II B. Then we could copy number 18 into A[3]. In fact. Given an array of 1023 elements. Thus. 1. there will be one item left to test. This restricts our next iteration through the loop to the top half of the array. If (ITEM == A [J]) Then 3. In this way. Print: ITEM found at location J P a g e | 12 Department of Computer Science & Engineering GEC . to insert the number 18. we can search the entire array in only 10 comparisons. To improve the efficiency of insert and delete operations. Write C programs that use both recursive and non recursive functions to perform Linear search for a Key value in a given list. DESCRIPTION: If the data is sorted. we can narrow the search to 511 elements in one comparison. Variables Lb and Ub keep track of the lower bound and upper bound of the array. a binary search may be done. the first iteration will leave 3 items to test. linked lists may be used. we set Ub to (M – 1). For example. each iteration halves the size of the array to be searched. then it must reside in the top half of the array. we may wish to insert or delete entries. Unfortunately. respectively. A similar problem arises when deleting numbers. After another comparison. After the second iteration. For example. an array is not a good arrangement for these operations. If the key we are searching for is less than the middle element. Repeat for J = 1 to N 2. and we‟re looking at only 255 elements. In addition to searching. This is a powerful method.

If (J > N) Then 6. Exit P a g e | 13 Department of Computer Science & Engineering GEC . Return [End of If] [End of For Loop] 5.II B. Print: ITEM doesn‟t exist [End of If] 7.Tech Data Stractures 4.

Set BEG = 1 and END = N 2. Set END = MID – 1 6. 1. Set MID = (BEG + END) / 2 [End of While Loop] 9.II B. ITEM is the value to be searched. If (A[MID] == ITEM) Then 10.Write C programs that use both recursive and non recursive functions to perform Binary search for a Key value in a given list. BEG denotes first element and END denotes last element in the array. Exit P a g e | 14 Department of Computer Science & Engineering GEC .Tech Data Stractures b). ALGORITHM : Binary Search ( ): Description: Here A is a sorted array having N elements. If (ITEM < A[MID]) Then 5. Repeat While (BEG <= END) and (A[MID] ? ITEM) 4. Print: ITEM exists at location MID 11. Set MID = (BEG + END) / 2 3. Set BEG = MID + 1 [End of If] 8. MID denotes the middle value. Print: ITEM doesn‟t exist [End of If] 13. Else 12. Else 7.

augment the original array with Fm-n numbers larger than the sought item and apply the above algorithm for n'=Fm. F1 = 1. Set k = m. proceed as follows: 1. If item is less than entry Fk-1. 6. If k = 0. P a g e | 15 Department of Computer Science & Engineering GEC .Write C programs that use both recursive and non recursive functions to perform Fibonacci search for a Key value in a given list. If item is greater than entry Fk-1. Test item against entry in position Fk-1. 3. discard entries from positions Fk-1 + 1 to n. 4. If n is not a Fibonacci number. discard entries from positions 1 to Fk-1.1 and go to 2. To test whether an item is in a list of n = F m ordered numbers.II B. ALGORITHM : Let Fk represent the k-th Fibonacci number where Fk+2=Fk+1 + Fk for k>=0 and F0 = 0. finish .Tech Data Stractures c).no match. 2. set k = k . finish. Set k = k . Renumber remaining entries from 1 to Fk-2.2 and go to 2. 5. If match. then let Fm be the smallest such number >n.

Write C programs that implement Bubble sort.II B.Tech Data Stractures Exercise 4: a). to sort a given list of integers in ascending order ALGORITHM: step1: take first two elements of a list and compare them step2: if the first elements grater than second then interchange else keep the values as it step3: repeat the step 2 until last comparison takes place step4: reapeat step 1 to 3 until the list is sorted P a g e | 16 Department of Computer Science & Engineering GEC .

Write C programs that implement Quick sort.II B.Tech Data Stractures b). to sort a given list of integers in ascending order ALGORITHM: step1: take first a list of unsorted values step2: take firstelement as 'pivot' step3: keep the firstelement as 'pivot' and correct its position in the list step4: divide the list into two based on first element step5: combine the list P a g e | 17 Department of Computer Science & Engineering GEC .

Tech Data Stractures c).Write C programs that implement Insertion sort.II B. to sort a given list of integers in ascending order ALGORITHM: step1: take a list of values step2: compare the first two elements of a list if first element is greaterthan second interchange it else keep the list as it is. P a g e | 18 Department of Computer Science & Engineering GEC . step3: now take three elements from the list and sort them as follows Step4::reapeat step 2 to 3 until the list is sorted.

A Semi-Heap as mentioned above is a Heap except that the root does not possess the property of a heap node. It begins by constructing a special type of binary tree. since after each "Heaping" of the set of data. to sort a given list of integers in ascending order Heap Sort Technique: Heap sort algorithm. Significance of a semi-heap . The following C function takes care of reheaping a set of data or a part of it. But it is possible to use the same array to heap the unordered list and compile the sorted list. is the maximum of all the elements in the set of data. Note: A Heap by definition is a special type of binary tree in which each node is greater than any of its descendants. Hence the sorting process basically consists of extracting the root node and reheaping the remaining set of elements to obtain the next largest element till there are no more elements left to heap.Tech Data Stractures Exercise 5: a). If N be the number of a node. then its left child is 2*N and the right child 2*N+1. by definition. is based on the concept of heaps. This is usually done by swapping the root of the heap with the end of the array and then excluding that element from any subsequent reheaping. A semi-heap is a binary tree in which all the nodes except the root possess the heap property.II B. one for the heap and the other to store the sorted data. Elementary implementations usually employ two arrays. the root is extracted and replaced by an element from the list. It is a complete binary tree. called heap. Write C programs that implement Heap sort. This type of a heap is significant in the discussion of Heap Sorting. This leaves us with a Semi-Heap. out of the set of data which is to be sorted. constituting the binary tree. Reheaping a Semi-Heap is particularily easy since all other nodes have already been heaped and only the root node has to be shifted downwards to its right position. P a g e | 19 Department of Computer Science & Engineering GEC . The root node of a Heap. as the name suggests.

Now that we have a downheaper. Note that. temp. But in C. what we need is the actual sorting routine. --i) { downHeap(a. child = 1 (not 0) */ In the function. } else return. for (i = (array_size/2 -1). int array_size) { int i.Tech Data Stractures void downHeap(int a[].II B. void heapsort(int a[]. If it does already conform to it. the loop breaks and the function returns to caller. array_size-1). } else { if (a[child] > a[child + 1]) maxchild = child. theoritically speaking. for eg. we generally express the indices of the nodes starting from 1 through size of the array. child. i >= 0.. while (root*2 < bottom) { child = root * 2 + 1. what basically happens is that. } } In the above function. a[root] = a[maxchild]. i. root = maxchild. if root = 0. int bottom) { int maxchild. } if (a[root] < a[maxchild]) { temp = a[root]. else maxchild = child + 1. we know that array indexing begins at 0. int root. and so the left child is child = root * 2 + 1 /* so. a[maxchild] = temp. both root and bottom are indices into the array. if (child == bottom) { maxchild = child. starting from root each loop performs a check for the heap property of root and does whatever necessary to make it conform to it. P a g e | 20 Department of Computer Science & Engineering GEC . Note that the function assumes that the tree constituted by the root and all its descendants is a Semi-Heap.

10 6 8 4 1 2 5 3 Second loop which extracts root and reheaps. i-1). i >= 0. i-1). the list is heaped in the for loop starting from the mid element (which is the parent of the right most leaf of the tree) of the list. --i) { downHeap(a. } Following this is the loop which actually performs the extraction of the root and creating the sorted list. --i) { int temp. --i) { int temp. i >= 0.Tech Data Stractures } for (i = array_size-1. a[0] = temp. } The following are some snapshots of the array during the sorting process. a[0] = temp. for (i = (array_size/2 -1). i >= 0. a[i] = a[0]. Notice the swapping of the ith element with the root followed by a reheaping of the list. before the actual sorting of data takes place. i. downHeap(a. 8 6 5 4 1 2 3 10 } pass 1 6 4 5 3 1 2 8 10 } pass 2 5 4 2 3 1 6 8 10 } pass 3 4 3 2 1 5 6 8 10 } pass 4 P a g e | 21 Department of Computer Science & Engineering GEC . temp = a[i]. for (i = array_size-1. The unodered list 8 6 10 3 1 2 5 4 After the initial heaping done by the first for loop. 0.II B. } } Note that. a[i] = a[0]. array_size-1). 0. downHeap(a. temp = a[i].

An example Assume that we have n integers in the range (0. Repeat the process using n bins. Using n bins. consider the list of integers: 36 9 0 25 1 49 64 16 81 4 n is 10 and the numbers all lie in (0.99). we placed each item in a bin indexed by the least significant decimal digit. we used the leading decimal digit to allocate items to bins. m = n2. We can apply this process to numbers of any size expressed to any suitable base or radix.n2) to be sorted. we will have: Bin 0 1 2 3 4 5 6 7 0 1 64 25 36 Content 81 4 16 8 - 9 9 49 Note that in this phase. 2. (For a bin sort. place ai into bin ai mod n. placing ai into bin floor(ai/n). As an example.) Sort them in two phases: 1. After the first phase. This results in a sorted list. Generalized Radix Sorting: P a g e | 22 Department of Computer Science & Engineering GEC . will produce: Bin Content 0 0 1 4 9 1 16 2 25 3 36 4 49 5 - 6 64 7 - 8 81 9 - In this second phase.II B. to sort a given list of integers in ascending order Radix Sorting : The bin sorting approach can be generalized in a technique that is known as radix sorting. and we would have an O(n+m) = O(n2) algorithm.Tech Data Stractures b). being careful to add each item to the end of the bin. being careful to append to the end of each bin. Repeating the process.Write C programs that implement Radix sort.

eg 1900 < year <= 2000.j++) bin[j] = EMPTY. then using the next significant "digit". and that each fi has si discrete values. each with bounded ranges.k-1. Assume that the key of the item to be sorted has k fields. int month. placing each item after all the items already in the bin. for(j=0. } } O(si) O(n) O(si) Total P a g e | 23 Department of Computer Science & Engineering GEC . fi|i=0.. suppose that the sorting key is a sequence of fields.i<k. If the ranges for day and month are limited in the obvious way.II B. and so on.Tech Data Stractures We can further observe that it's not necessary to use the same radix in each phase.j<si.i++) { for(j=0. int year. } date. then a generalised radix sort procedure can be written: radixsort( A.j++) concatenate bin[j] onto the end of A.j++) { move Ai to the end of bin[Ai->fi] } for(j=0.j<n. In all cases.j<si. and the range for year is suitably constrained. then we can apply the same procedure except that we'll employ a different number of bins in each phase. n ) { for(i=0. eg the key is a date using the structure: typedef struct t_date { int day. we'll sort first using the least significant "digit" (where "digit" here means a field with a limited range).

II B. If k is allowed to increase with n. Thus. Another way of looking at this is to note that if the range of the key is restricted to (0. so that k = logn. then we will be able to use the radix sort approach effectively if we allow duplicate keys when n>bk. This result depends on k being constant. If the key length were allowed to increase with n. the keys are integers in (0. it takes log2n binary digits to represent an integer <n. However. then the keys can be viewed as k-digit base-b integers. we need to have logn phases. and the radix sort is the same as quick sort! P a g e | 24 Department of Computer Science & Engineering GEC . bk-1). each taking O(n) time. si = b for all i and the time complexity becomes O(n+kb) or O(n). then we would have: . as n increases. For example.Tech Data Stractures Now if. for some constant k. then k must increase to at least logbn. then we have a different picture. for example.bk-1). Thus. if we need to have unique keys.

MID. Set I = I + 1 and K = K + 1 8. K = BEG 4. Call Merge Sort (A. BEG. Set MID = (BEG + END) / 2 3. 1. Set A[K] = B[I] 7. MID) 4. Set A[K] = B[J] 10. Exit Merge Array ( A. BEG is the lower bound and END is the upper bound. B is an empty array. If (BEG < END) Then 2. END ) Description: Here A is an unsorted array. END) 5. Repeat For I = BEG to END 2. END) [End of If] 6. BEG. to sort a given list of integers in ascending order Algorithm to Sort an Array using MERGE SORT Merge Sort ( A. Repeat While (I <= MID) and (J <= END) 5.II B. Call Merge Sort (A. BEG is the lower bound. END is the upper bound and MID is the middle value of array. Set J = J + 1 and K = K + 1 [End of If] [End of While Loop] P a g e | 25 Department of Computer Science & Engineering GEC . 1.Tech Data Stractures c). Call Merge Array (A. BEG. Set I = BEG. If (B[I] <= B[J]) Then [Assign smaller value to A] 6. BEG.Write C programs that implement Merge sort. Else 9. Set B[I] = A[I] [Assign array A to B] [End of For Loop] 3. MID. J = MID + 1. MID + 1. END ): Description: Here A is an unsorted array.

Repeat While (J <= END) 17. Set A[K] = B[I] 14. Set A[K] = B[J] 18. Set J = J + 1 and K = K + 1 [End of While Loop] [End of If] 19.Tech Data Stractures 11. Repeat While (I <= MID) has exhausted or not] 13.II B. Else 16. Exit P a g e | 26 Department of Computer Science & Engineering GEC . If (I <= MID) Then [Check whether first half 12. Set I = I + 1 and K = K + 1 [End of While Loop] 15.

Print: ITEM deleted [End of If] 7. Else 4.Tech Data Stractures Exercise 6: a) Write C programs that implement stack (its operations) using arrays Algorithm to Push Item into Stack Push ( ): Description: Here STACK is an array with MAX locations. Exit Algorithm to Pop Item from Stack Pop ( ): Description: Here STACK is an array with MAX locations. Print: ITEM inserted [End of If] 7. 1. If (TOP == 0) Then [Check for underflow] 2. Set TOP = TOP . If (TOP == MAX) Then [Check for overflow] 2. Set TOP = TOP + 1 [Increment TOP by 1] 5. Set STACK[TOP] = ITEM [Assign ITEM to top of STACK] 6. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM] 5. Print: Underflow 3. Print: Overflow 3. Exit P a g e | 27 Department of Computer Science & Engineering GEC . Else 4. TOP points to the top most element and ITEM is the value to be inserted.II B. 1. TOP points to the top most element.1 [Decrement TOP by 1] 6.

Print: ITEM deleted [End of If] 7. Set STACK[TOP] = ITEM [Assign ITEM to top of STACK] 6. Else 4.Tech Data Stractures b) Write C programs that implement stack (its operations) using Linked list Algorithm: Algorithm to Push Item into Stack Push ( ): Description: Here STACK is an array with MAX locations.II B. Print: Overflow 3. Print: ITEM inserted [End of If] 7. Exit Algorithm to Pop Item from Stack Pop ( ): Description: Here STACK is an array with MAX locations. Set TOP = TOP + 1 [Increment TOP by 1] 5. Print: Underflow 3. Exit P a g e | 28 Department of Computer Science & Engineering GEC . TOP points to the top most element. 1. Else 4. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM] 5. If (TOP == 0) Then [Check for underflow] 2. If (TOP == MAX) Then [Check for overflow] 2.1 [Decrement TOP by 1] 6. TOP points to the top most element and ITEM is the value to be inserted. Set TOP = TOP . 1.

If the scanned element is: (i) an operand then add it to P. [End of Step 4 If] [End of step 3 For Loop] P a g e | 29 Department of Computer Science & Engineering GEC . Pop from stack and add to P each operator (i) until a left parenthesis is encountered. (viii) a right parenthesis then: b. Add “)” right parenthesis to the end of expression I. 1. (ii) a left parenthesis then push it onto stack. (i) (ii) 5. until the stack becomes empty. 2.Tech Data Stractures Exercise 7: a) Write a C program that uses Stack operations to Convert infix expression into postfix expression Algorithm to Transform Infix Expression into Postfix Expression using Stack Transform ( ): Description: Here I is an arithmetic expression written in infix notation and P is the equivalent postfix expression generated by this algorithm. Algorithm.II B. Scan I from left to right and repeat step 4 for each element of I a. Push “(“ left parenthesis onto stack. Exit. 3. (vii) (ii) Add newly scanned operator to stack. Remove the left parenthesis. 4. c. (iii) an operator then: (iv) Pop from stack and add to P each operator (v) which has the same or higher precedence then (vi) the scanned operator.

P a g e | 30 Department of Computer Science & Engineering GEC . where A is the top element and B is the next to top element. 2) Scan P from left to right and repeat steps 3 & 4 for each element i) of P until “)” is encountered. 4) If an operator ? is encountered then: i) ii) iii) iv) v) vi) Pop the top two elements from stack. 1) Add a “)” right parenthesis at the end of P.II B. Evaluate B ? A. [End of Step 4 If] [End of step 2 For Loop] 5) Set VALUE equal to the top element on the stack. push it onto stack. 3) If an operand is encountered. 6) Exit. Place the result of (b) back on stack.Tech Data Stractures Algorithm to Evaluate Postfix Expression using Stack Evaluate ( ): Description: Here P is a postfix expression and this algorithm evaluates it.

1.II B. If (FRONT == REAR) Then [Check if only one element is left] (a) Set FRONT = 0 (b) Set REAR = 0 P a g e | 31 Department of Computer Science & Engineering GEC . FRONT and REAR points to the front and rear of the QUEUE.Tech Data Stractures b). ITEM = QUEUE[FRONT] 5. If (FRONT == 0) Then [Check for underflow] 2. Print: Overflow 3. If (REAR == N) Then [Check for overflow] 2. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 7. FRONT and REAR points to the front and rear of the QUEUE. Else 6. Print: Underflow 3. Else 4. Algorithm to Insert Item into Queue Insert ( ): Description: Here QUEUE is an array with N locations. Print: ITEM inserted [End of Step 1 If] 9. ITEM is the value to be inserted. Else 4. Exit Algorithm to Delete Item from Queue Delete ( ): Description: Here QUEUE is an array with N locations. Write C programs that implement Queue (its operations) using arrays. QUEUE[REAR] = ITEM 8. If (FRONT and REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1 (b) Set REAR = 1 5. 1.

Tech Data Stractures 6. Else 7. Print: ITEM deleted [End of Step 1 If] 9.II B. Exit P a g e | 32 Department of Computer Science & Engineering GEC . Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If] 8.

If (FRONT == REAR) Then [Check if only one element is left] P a g e | 33 Department of Computer Science & Engineering GEC . FRONT and REAR points to the front and rear of the QUEUE.Tech Data Stractures c). FRONT and REAR points to the front and rear of the QUEUE. Print: Overflow 3. Else 4. If (REAR == N) Then [Check for overflow] 2.Write C programs that implement Queue (its operations) using linked lists /*Queue Using Linked List*/ ALGORITHM: Algorithm to Insert Item into Queue Insert ( ): Description: Here QUEUE is an array with N locations. Print: ITEM inserted [End of Step 1 If] 9. Else 4. If (FRONT == 0) Then [Check for underflow] 2.II B. If (FRONT and REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1 (b) Set REAR = 1 5. ITEM = QUEUE[FRONT] 5. Else 6. Exit Algorithm to Delete Item from Queue Delete ( ): Description: Here QUEUE is an array with N locations. 1. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 7. QUEUE[REAR] = ITEM 8. 1. ITEM is the value to be inserted. Print: Underflow 3.

Else 7. If (FRONT == 1 and REAR == N) or (FRONT == REAR + 1) Then 2. Exit P a g e | 34 Department of Computer Science & Engineering GEC . Else 8. Print: ITEM deleted [End of Step 1 If] 9. Set REAR = 1 7. Else If (REAR == N) Then [If REAR reaches end if QUEUE] 6. 1. If (REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1 (b) Set REAR = 1 5. Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If] 8. FRONT and REAR points to the front and rear elements of the QUEUE. Set QUEUE[REAR] = ITEM 10. ITEM is the value to be inserted.Tech Data Stractures (a) Set FRONT = 0 (b) Set REAR = 0 6. Print: Overflow 3. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 9. Else 4.II B. Exit Algorithm to Insert Item into Circular Queue Insert Circular ( ): Description: Here QUEUE is an array with N locations. Print: ITEM inserted [End of Step 1 If] 11.

REV will maintain the reverse list. Else 4.Tech Data Stractures Exercise 8: a) Write a C program that uses functions to create a Singly linked list ALGORITHM: Description: Here START is a pointer variable which contains the address of first node. PREV = NULL 2. NEW is a pointer variable which will contain address of new node. 1. PREV = PTR 5. Repeat While (PTR!= NULL) 3. 1. PREV->LINK = REV [End of While Loop] 7. PTR will point to the current node and PREV will point to the previous node. Set PTR = START. Print: Linked-List is empty. REV = PREV 4. It must have at least one node 3. START = PREV 8. Exit ALGORITHM TO INSERT ITEM AFTER A SPECIFIC NODE INSERT SPECIFIC ( ): Description: Here START is a pointer variable which contains the address of first node. NEW = START 5. Repeat While (PTR != NULL) P a g e | 35 Department of Computer Science & Engineering GEC . PTR = PTR->LINK 6. If (START == NULL) Then 2.II B. Set PTR = START. N is the value after which new node is to be inserted and ITEM is the value to be inserted.

ELSE 13. PTR = PTR->LINK P a g e | 36 Department of Computer Science & Engineering GEC . Print: ITEM inserted 12. NEW->LINK = PTR->LINK 10.II B. NEW->INFO = ITEM 9.Tech Data Stractures 6. PTR->LINK = NEW 11. NEW = New Node 8. If (PTR->INFO == N) Then 7.

II B. Else 12. START->INFO = ITEM 10. Repeat While (PTR != NULL) 14. Else 6. PTR = START 8. PREV = PREV->LINK 17. Return 20. If (ITEM < START->INFO) Then [Check whether ITEM is less then value in first node] 7. If (START == NULL) Then [Check whether list is empty] 2. Else If (PTR->LINK == NULL) Then [Check whether PTR reaches last node] 21. START = New Node [Create a new node] 3. PREV->LINK = PTR 19. START = New Node 9. START->LINK = NULL [Assign NULL to LINK field] 5. PREV is a pointer variable which contains address of previous node. ITEM is the value to be inserted. START->LINK = PTR 11. 1. If (ITEM < PTR->INFO) Then 15. PREV->LINK = New Node 16. Set PTR = START. PREV = START 13. PREV->INFO = ITEM 18.Tech Data Stractures b) Write a C program that uses functions to perform insertion operation on a Singly linked list ALGORITHM: INSERTED ( ): Description: Here START is a pointer variable which contains the address of first node. PTR->LINK = New Node P a g e | 37 Department of Computer Science & Engineering GEC . START->INFO = ITEM [Assign ITEM to INFO field] 4.

Exit P a g e | 38 Department of Computer Science & Engineering GEC . PTR->INFO = ITEM 24. PTR = PTR->LINK [End of Step 14 If] [End of While Loop] [End of Step 6 If] [End of Step 1 If] 29. Else 27. PREV = PTR 28. PTR = PTR->LINK 23. Return 26.II B.Tech Data Stractures 22. PTR->LINK = NULL 25.

Else 9. If (START == NULL) Then [Check whether list is empty] 2. Print: Linked-List is empty. PREV = PTR [Assign PTR to PREV] 7. Exit P a g e | 39 Department of Computer Science & Engineering GEC . PREV is a pointer variable which points to previous node. If (START->LINK == NULL) Then [If only one node is left] 10.Tech Data Stractures c) Write a C program that uses functions to perform deletion operation on a Singly linked list ALGORITHM: DELETE LAST ( ): Description: Here START is a pointer variable which contains the address of first node. Delete PTR 11. PTR = PTR->LINK [Move PTR to next node] [End of While Loop] 8. START = NULL [Assign NULL to START] 11. 3. PREV->LINK = NULL [Assign NULL to link field of second last node] [End of Step 9 If] 10. 1. PREV = START 5. Repeat While (PTR->LINK != NULL) 6. ITEM is the value to be deleted. Print: ITEM deleted [End of Step 1 If] 12. PTR is a pointer variable which contains address of node to be deleted. Else 4. ITEM = PTR->INFO [Assign INFO of last node to ITEM] 9.II B. PTR = START.

3.II B. Exit [End of If] 4. if they are not equal.Tech Data Stractures Exercise 9: d) Adding two large integers which are represented in linked list fashion. we have to check whether the rows of array A are equal to the rows of array B or the columns of array A are equal to the columns of array B. then first for loop iterates to the total number of rows i. ALGORITHM: ADD ( ): Description: Here A is a two – dimensional array with M rows and N columns and B is a two –dimensional array with X rows and Y columns. then addition is not possible and the algorithm exits. Exit Explanation: First. Repeat For J = 1 to N 6. the element A[I][J] is added to the element B[I][J] and is stored in C[I][J] by the statement: C[I][J] = A[I][J] + B[I][J P a g e | 40 Department of Computer Science & Engineering GEC . N. 1. M and the second for loop iterates to the total number of columns i. If (M ? X) or (N ? Y) Then 2. This algorithm adds these two arrays. Print: Addition is not possible.e. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7. In step 6. But if they are equal. Repeat For I = 1 to M 5.e.

PREV = NULL 2. REV will maintain the reverse list. Repeat While (PTR != NULL) 3. Set PTR = START. REV = PREV 4. Exit P a g e | 41 Department of Computer Science & Engineering GEC . ALGORITHM: Algorithm to Reverse a Linked List Reverse ( ): Description: Here START is a pointer variable which contains the address of first node. PTR will point to the current node and PREV will point to the previous node.Tech Data Stractures e) Write a C program to reverse elements of a Single linked list. 1. PTR = PTR->LINK 6. START = PREV 8. PREV->LINK = REV [End of While Loop] 7. PREV = PTR 5.II B.

Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7.e. ALGORITHM: Description: Here A is a two – dimensional array with M rows and N columns and B is a two – dimensional array with X rows and Y columns. Repeat For I = 1 to M 5. if they are not equal. In step 6. Exit [End of If] 4. we have to check whether the rows of array A are equal to the rows of array B or the columns of array A are equal to the columns of array B. M and the second for loop iterates to the total number of columns i. This algorithm adds these two arrays. 3.Tech Data Stractures f) Write a C program to representation the given Sparse matrix using arrays. Print: Addition is not possible. Repeat For J = 1 to N 6. If (M ? X) or (N ? Y) Then 2.II B. Exit Explanation: First. then first for loop iterates to the total number of rows i. the element A[I][J] is added to the element B[I][J] and is stored in C[I][J] by the statement: C[I][J] = A[I][J] + B[I][J P a g e | 42 Department of Computer Science & Engineering GEC . 1.e. then addition is not possible and the algorithm exits. N. But if they are equal.

e. Exit Explanation: First we check whether the rows of A are equal to columns of B or the columns of A are equal to rows of B. the first for loop iterates to total number of columns of A i. 3. the element A[I][K] is multiplied with B[K][J] and added to C[I][J] and the result is assigned to C[I][J] by the statement: C[I][J] = C[I][J] + A[I][K] * B[K][J P a g e | 43 Department of Computer Science & Engineering GEC .Tech Data Stractures g) Write a C program to representation the given Sparse matrix using linked list ALGORITHM: Description: Here A is a two – dimensional array with M rows and N columns and B is a two – dimensional array with X rows and Y columns. In step 6. Y.e. Set C[I][J] = C[I][J] + A[I][K] * B[K][J] [End of Step 7 For Loop] [End of Step 5 For Loop] [End of Step 4 For Loop] [End of If] 9. if they are equal. X.II B.e. Repeat For J = 1 to X 6. Repeat For I = 1 to N 5. then multiplication is not possible. all the elements of C are set to zero. Repeat For K = 1 to Y 8. 1. This algorithm multiplies these two arrays. Set C[I][J] = 0 7. If (M ? Y) or (N ? X) Then 2. If they are not equal. N and the second for loop iterates to the total number of rows of B i. In step 8. Else 4. Print: Multiplication is not possible. Then the third for loop iterates to total number of columns of B i. But.

d in item let ISMTBT(CREATE)::=true ISMTBT(MAKEBT(p.r))::=false LCHILD(MAKEBT(p.d. LCHILD(CREATE)::=error DATA(MAKEBT(p. For binary trees we distinguish between the subtree on the left and on the right.r))::d. We can define the data structure binary tree as follows: structure BTREE declare CREATE( ) --> btree ISMTBT(btree.II B.r))::=p. RCHILD(CREATE)::=error end end BTREE P a g e | 44 Department of Computer Science & Engineering GEC . Definition: A binary tree is a finite set of nodes which is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree.btree) --> btree LCHILD(btree) --> btree DATA(btree) --> item RCHILD(btree) --> btree for all p.btree) --> boolean MAKEBT(btree.d.item.item.d. DATA(CREATE)::=error RCHILD(MAKEBT(p. i.there is no node with degree greater than two.d. Thus a binary tree is really a different object than a tree.e.Tech Data Stractures Exercise10: a) Write a C program to Create a Binary Tree of integers ALGORITHM: Binary tree is an important type of structure which occurs very often. It is characterized by the fact that any node can have at most two branches. Also a binary tree may have zero nodes.r))::=r. whereas for trees the order of the subtree was irrelevant.r in btree..

II B.value) If RightPointer(TreeNode) != NULL Then P(TreeNode.value) If LeftPointer(TreeNode) != NULL Then P(TreeNode. H IN-ORDER The second(middle) type of traversal is in-order whose code looks like the following: sub P(TreeNode) If LeftPointer(TreeNode) != NULL Then P(TreeNode.RightNode) end sub This can be summed up as Visit the root node (generally output this) Traverse to left subtree Traverse to right subtree And outputs the following: F. B.LeftNode) If RightPointer(TreeNode) != NULL Then P(TreeNode.Tech Data Stractures b) Write a recursive C program.RightNode) end sub P a g e | 45 Department of Computer Science & Engineering GEC . I.LeftNode) Output(TreeNode. ALGORITHM: PREORDER The first type of traversal is pre-order whose code looks like the following: sub P(TreeNode) Output(TreeNode. E. D. A. C. for Traversing a binary tree in preorder. G. inorder and postorder.

G. D.II B. C. I POST-ORDER The last type of traversal is post-order whose code looks like the following: sub P(TreeNode) If LeftPointer(TreeNode) != NULL Then P(TreeNode. F.RightNode) Output(TreeNode. E.Tech Data Stractures This can be summed up as Traverse to left subtree Visit root node (generally output this) Traverse to right subtree And outputs the following: A. B. I.LeftNode) If RightPointer(TreeNode) != NULL Then P(TreeNode.value) end sub This can be summed up as Traverse to left subtree Traverse to right subtree Visit root node (generally output this) And outputs the following: A. B. D. E. H. G. H. C. F P a g e | 46 Department of Computer Science & Engineering GEC .

{Creates a new BST T containing the elements of A} InOrder (root of T). if root is empty then return else InOrder (left child of root). {Sorts the elements in T using an inorder traversal} b) Write a C program to insert a note into a BST. output the value in root. CreateBST (A). index 1.II B. root) Iteratively insert a value v into a binary search tree (BST) with root named root. InOrder (right child of root). end while return T Algorithm InOrder (root) Perform an inorder (second-visit) traversal of the BST with root named root.Tech Data Stractures Exercise 11: a) Write a C program to Create a BST Algorithm CreateBST (A) Create a binary search tree (BST) from an array A with N elements. while index N do InsertBST (A[index ]. root). Binary Search Tree Algorithms Algorithm Insert BST (v. index index + 1. end if Algorithm TreeSort (A) Sort the elements in array A using a binary search tree (BST). root the root of a new binary search tree named T. P a g e | 47 Department of Computer Science & Engineering GEC .

end if else if the right child of node exists then node right child of node. P a g e | 48 Department of Computer Science & Engineering GEC . else node root. else insert v as the left child of node. else if v value stored in root then if the left child of root exists then InsertBST (v. left child of root).Tech Data Stractures if root is empty then root v. end if end if end loop end if Algorithm InsertBST (v. we will explicitly exit the loop after v is inserted} if v value stored in node then if the left child of node exists then node left child of node.II B. exit the loop. else insert v as the right child of node. exit the loop. root) Recursively insert a value v into a binary search tree (BST) with root named root. else insert v as the left child of root. if root is empty then root v. loop {an infinite loop.

that is. 2) IF <element> is found.Tech Data Stractures end if else if the right child of root exists then InsertBST (v. the <node> to be deleted has <left> and <right> subtrees. // In both cases a&b the delete operation fails. that is.II B. IF <root> == NULL (tree is empty) b. end if end if end if c) Write a C program to delete a note from a BST. the <left> subtree is empty. // the easiest case case 2: The <node> to be deleted has no <left> subtree. else insert v as the right child of root. Search the BST for the element to be deleted. // the hardest case P a g e | 49 Department of Computer Science & Engineering GEC . the <node> to be deleted is a leaf. but it has nonempty <right> subtree. DELETION ALGORITHM 1) Check for the cases that the delete operation fails: a. case 4: The <node> to be deleted has nonempty <left> and <right> subtrees. IF <element> is not found (there is no such element in the tree). the <right> subtree is empty. that is. but it has nonempty <left> subtree. case 3: The <node> to be deleted has no <right> subtree. that is. right child of root). then the delete operation has four cases: case 1: The <node> to be deleted has no <left> and <right> subtrees.

if there is no edge from I to j (In the problem ∞ is replaced with some large number 99999) The distance of a directed path „p‟ is defined to be the „S‟ denotes the Starting vertex „T‟ denotes the Terminal vertex Disjkstra‟s Alogrithm is the most efficient shortest path Alo grithm P a g e | 50 Department of Computer Science & Engineering GEC . d ij >=0 D ij=0 D ij=∞.II B.Tech Data Stractures Exercise 12: a) Write a C program algorithm to compute the shortest path of a graph using Dijkstra’s To implement Dijkstra’s Algorithm DESCRIPTION: Shortest path from a specified vertex „S‟ to another specified vertex „T‟ can be stated as follows: A simple weighted Graph „G‟of n vertices is described by a n*n matrix D = [d ij] Where d ij=length (or distance or weight) of the directed edge from vertex i to vertex j.

A ∞ 7 7 4 4 4 4 4 4 4 B 0 0 0 0 0 0 0 0 0 0 C ∞ 1 1 1 1 1 1 1 1 1 D ∞ ∞ ∞ ∞ ∞ 14 14 12 12 12 E ∞ ∞ ∞ 5 5 5 5 5 5 5 F ∞ ∞ ∞ 4 4 4 4 4 4 4 G ∞ ∞ ∞ ∞ ∞ 11 11 11 7 7 Destination vertex gets permanently labeled.II B.Tech Data Stractures EXAMPLE: Finding the shortest path from vertex „B‟ to G:  Starting vertex B is labeled 0.  Smallest label become permanent  Successor of „C‟ gets labeled. P a g e | 51 Department of Computer Science & Engineering GEC .  All successor of B get labeled.

visited[maxVertices]={0} represents the vertex that have been visited. Algorithm: Input Format: Graph is directed and weighted. to solve the all-pairs shortest path problem on directed graphs. init() function. It finds shortest path between all nodes in a graph. distance[maxVertices][maxVertices] represents the weight of the edge between the two vertices or distance between two vertices. For iter=0 to maxVertices – 1 For jter=0 to maxVertices – 1 if(iter == jter) distance[iter][jter] = 0 //Distance between two same vertices is 0 else distance[iter][jter] = INF//Distance between different vertices is INF jter + 1 P a g e | 52 Department of Computer Science & Engineering GEC .II B. First two integers must be number of vertices and edges which must be followed by pairs of vertices which has an edge between them. maxVertices represents maximum number of vertices that can be present in the graph. Initialize the distance between two vertices using init() function.Tech Data Stractures b) Write a C program to find the minimum spanning tree using Warshall’s Algorithm ALGORITHM: Warshall algorithm is a dynamic programming formulation. represents the size of every vertex i. size[maxVertices] is initialed to{0}. The algorithm considers the intermediate vertices of a simple path are any vertex present in that path other than the first and last vertex of that path. If finds only the lengths not the path. the number of edges corresponding to the vertex.e. vertices represent number of vertices and edges represent number of edges in thegraph. graph[i][j] represent the weight of edge joining i and j.It takes the distance matrix as an argument.

to.II B. via For from=0 to vertices-1 For to=0 to vertices-1 For via=0 to vertices-1 distance[from][to] = min(distance[from][to]. INF is a very large integer value.distance[from] [via]+distance[via][to]) via + 1 to + 1 from + 1 This finds the minimum distance from from vertex to to vertex using the min function. Initialize and input the graph. Output the distance between every two vertices. Call Floyd Warshall function. P a g e | 53 Department of Computer Science & Engineering GEC . • Initialize integer type from. It checks it there are intermediate vertices between the from and to vertex that form the shortest path between them • min function returns the minimum of the two integers it takes as argument. • It takes the distance matrix (distance[maxVertices][maxVertices]) and number of vertices as argument (vertices).Tech Data Stractures iter + 1 Where.

II B.Tech

Data Stractures

ADD ON PROGRAMS :

1. Write a C program on Circular Queue operations

Circular Queue
A circular queue is a Queue but a particular implementation of a queue. It is very efficient. It is also quite useful in low level code, because insertion and deletion are totally independant, which means that you don't have to worry about an interrupt handler trying to do an insertion at the same time as your main code is doing a deletion. Algorithm for Insertion:Step-1: If "rear" of the queue is pointing to the last position then go to step-2 or else step-3 Step-2: make the "rear" value as 0 Step-3: increment the "rear" value by one Step-4: 1. if the "front" points where "rear" is pointing and the queue holds a not NULL value for it, then its a "queue overflow" state, so quit; else go to step-4.2 2. insert the new value for the queue position pointed by the "rear" Algorithm for deletion:Step-1: If the queue is empty then say "empty queue" and quit; else continue Step-2: Delete the "front" element Step-3: If the "front" is pointing to the last position of the queue then step-4 else step-5 Step-4: Make the "front" point to the first position in the queue and quit Step-5: Increment the "front" position by one

P a g e | 54

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

2. Write a C program on Evaluation on Postfix Expression

Postfix Evaluation
Infix Expression : Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression. Postfix Expression : The Postfix(Postorder) form of the above expression is "23*45/-". Postfix Evaluation : In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The algorithm for the conversion is as follows :    Scan the Postfix string from left to right. Initialise an empty stack. If the scannned character is an operand, add it to the stack. If the scanned character is an operator, there will be atleast two operands in the stack.  If the scanned character is an Operator, then we store the top most element of the stack(topStack) in a variable temp. Pop the stack. Now evaluate topStack(Operator)temp. Let the result of this operation be retVal. Pop the stack and Push retVal into the stack. Repeat this step till all the characters are scanned.  After all characters are scanned, we will have only one element in the stack. Return topStack.

Example : Let us see how the above algorithm will be imlemented using an example. Postfix String : 123*+4Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3, which are operands. Thus they will be pushed into the stack in that order.

Expression

Stack

Next character scanned is "*", which is an operator. Thus, we pop the top two elements from the stack and perform the "*" operation with the two operands. The second operand will be the first element that is popped.

P a g e | 55

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Expression

Stack

The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.

Expression

Stack

Next character scanned is "+", which is an operator. Thus, we pop the top two elements from the stack and perform the "+" operation with the two operands. The second operand will be the first element that is popped.

Expression

Stack

The value of the expression(1+6) that has been evaluated(7) is pushed into the stack.

Expression

Stack

Next character scanned is "4", which is added to the stack.

Expression

Stack

Next character scanned is "-", which is an operator. Thus, we pop the top two elements from the stack and perform the "-" operation with the two operands. The second operand will be the first element that is popped.

P a g e | 56

Department of Computer Science & Engineering

GEC

Tech Data Stractures Expression Stack The value of the expression(7-4) that has been evaluated(3) is pushed into the stack. Expression Stack Now.II B. End result : Postfix String : 123*+4Result : 3 P a g e | 57 Department of Computer Science & Engineering GEC . since all the characters are scanned. the remaining element in the stack (there will be only one element in the stack) will be returned.

When this new vertex has been explored. or some other numeric value associated with the edge. A graph can be thought of a collection of vertices (V) and edges (E). or cost. An undirected graph is a graph where the edge set in an unordered pair. At this time of exploration of the new vertex u begins. this algorithm visits all vertices reachable //from v. Algorithm DFS(v) // Given an undirected(directed) graph G=(V. is a graph where the edge set is an ordered pair. (i. E) 2. G and visited[] are global. A weighted graph is graph which has a value associated with each edge.e. That is. The search process is best described recursively in the following algorithm. weighted or unweighted. 5. or undirected. Graphs can be directed. 4. edge 1 being connected to edge 2 does not imply that edge 2 is connected to edge 1. { visited[v]:=1. or digraph. } P a g e | 58 Department of Computer Science & Engineering GEC . This can be a distance. the exploration of v continues. The search terminates when all reached vertices have been fully explored. That is. 3. for each vertex w adjacent from v do { if (visited[w]=0) then DFS(w). so we write. ALGORITHM FOR DEPTH FIRST SEARCH AND TRAVERSAL: A depth first search of a graph differs from a breadth first search in that the exploration of a vertex v is suspended as soon as a new vertex is reached.II B. A directed graph.E) with n vertices and an //array visited [] initially set to zero. Write a C program search the elements using Breadth First Search Algorithm & Depth First Search Algorithm DESCRIPTION: 1. G = (V. edge 1 being connected to edge 2 does imply that edge 2 is connected to edge 1. it has direction – trees are special kinds of directed graphs).Tech Data Stractures 3.

{ u:=v. edge 1 being connected to edge 2 does not imply that edge 2 is connected to edge 1. That is. visited[I=1 if I has already been visited. Graphs can be directed. A graph can be thought of a collection of vertices (V) and edges (E).II B.e. or undirected. or cost. E) 2. Exploration continues until no unexplored vertex is left. repeat { for all vertices w adjacent from u do P a g e | 59 Department of Computer Science & Engineering GEC . //q is a queue of unexplored vertices visited[v]:=1. The graph G //and array visited are global. 4. The newly visited vertices have not been explored and or put on to the end of a list of unexplored list of vertices. weighted or unweighted. so we write. A vertex is said to have been explored by an algorithm when the algorithm has visited all vertices adjacent from it. The list of unexplored vertices operates as a queue and can be represented using any of the standard queue representations. 5. or some other numeric value associated with the edge. All unvisited vertices adjacent from v are visited next. it has direction – trees are special kinds of directed graphs). This can be a distance. For //any node I. A directed graph. (i. Algorithm BFS(v) //A breadth first search of G is carried out beginning at vertex v. visited[] is initialized to zero. edge 1 being connected to edge 2 does imply that edge 2 is connected to edge 1. These are new unexplored vertices. The first vertex on this list is the next to be explored. 3. or digraph. G = (V. A weighted graph is graph which has a value associated with each edge. ALGORITHM FOR BREADTH FIRST SEARCH AND TRAVERSAL: In Breadth first search we start at vertex v and mark it as having been reached (visited) the vertex v is at this time said to be unexplored. is a graph where the edge set is an ordered pair.Tech Data Stractures DESCRIPTION: 1. That is. Vertex v has now been explored. An undirected graph is a graph where the edge set in an unordered pair.

//no unexplored vertex delete u from q.Tech Data Stractures { if (visited[w]=0) then { add w to q. } Algorithm BFT(G. //w is unexplored visited[w]:=1. //get first unexplored vertex }until(false). n) //Breadth first traversal of G { for I:=1 to n do //mark all vertices unvisited visited[I]:=0. for I:=1 to n do if (visited[I]=0) then BFS(i). } } if q is empty then return.II B. } P a g e | 60 Department of Computer Science & Engineering GEC .

and Deletion can be implemented in worst case O (log n) time.e. Definition: An AVL tree is a binary search tree in which 1. Search. The left subtree and the right subtree are themselves AVL trees 3. insertions and deletions on AVL trees AVL Trees: Also called as: Height Balanced Binary Search Trees. P a g e | 61 Department of Computer Science & Engineering GEC . A node is said to be left-high if the left subtree has greater height if the right subtree has greater height / right-high equal if the heights of the LST and RST are the same Examples: Several examples of AVL trees are shown in Figure1. Insertion.. Write a C program to perform various operations i.Tech Data Stractures 4. The heights of the right subtree and left subtree of the root differ by at most 1 2.II B.

1| + | Fh . having the minimum number of nodes. Fr will have the minimum number of nodes among all AVL trees of height h--2. Similarly. respectively. Suppose Fl has height h-1 so that Fr has height h-2. Such trees are called Fibonacci trees. See Figure 3. Thus we have | Fh| = | Fh . of Fh. Fh can be visualized as in Figure 2. P a g e | 62 Department of Computer Science & Engineering GEC . Note that Fr has to be an AVL tree having the minimum number of nodes among all AVL trees with height of h-1.II B. we will pose the following question: What is the minimum number of nodes (sparsest possible AVL tree) an AVL tree of height h can have? Let Fh be an AVL tree of height h.2| + 1 Where | Fr| denotes the number of nodes in Fr. Let Fl and Fr be AVL trees which are the left subtree and right subtree. Then Fl or Fr must have height h-2.Tech Data Stractures Figure 2: An AVL tree with height h Maximum Height of an AVL Tree: What is the maximum height of an AVL tree having exactly n nodes? To answer this question.

the resulting tree may violate the (stringent) AVL property.44log| Fn| The sparsest possible AVL tree with n nodes has height h 1. Using the approximate formula for Fibonacci numbers. P a g e | 63 Department of Computer Science & Engineering GEC . we get | Fh | + 1 h 1.1| + 1) + (| Fh . we use rotations. See Figure 4.44log n The worst case height of an AVL tree with n nodes is 1.2| + 1) Thus the numbers | Fh| + 1 are Fibonacci numbers. Adding 1 to both sides.Tech Data Stractures Figure 3: Fibonacci trees Note that | F0| = 1 and | F1| = 2.II B. To reinstate the AVL property.44log n Algorithm for Insertions and Deletions into an AVL Trees: While inserting a new node or deleting an existing node. we get | Fh| + 1 = (| Fh .

P a g e | 64 Department of Computer Science & Engineering GEC . no more than [h/2] rotations are required to fix the AVL property. not necessarily the root.II B. Fixing the AVL property involves doing a series of single or double rotations. right = temp left = p . Problem Scenarios in AVL Tree Insertions  left sub tree of node has degree higher by >= 2  left child of node is left high (A)  left child or node is right high (B)  right sub tree has degree higher by >= 2  right child of node is left high (C)  right child or node is right high (D) The AVL tree property may be violated at any node. left .Tech Data Stractures Figure 4: Rotations in a binary search tree Rotation in a BST: Left rotation and right rotation can be realized by a three-way rotation of pointers. Double rotation involves a left rotation followed or preceded by a right rotation. Left rotation and right rotation preserve  BST property  Inorder ordering of keys  right . Left Rotation: Temp = p p temp p = temp . In an AVL tree of height h.

Tech Data Stractures Insertion: Problem Scenario 1: (Scenario D) Scenario A is symmetrical to the above. See Figure 5. Figure 5: Insertion in AVL trees: Scenario D P a g e | 65 Department of Computer Science & Engineering GEC .II B.

See Figure 6.Tech Data Stractures Insertion: Problem Scenario 2: (Scenario C) Scenario B is symmetrical to this. Figure 6: Insertion in AVL trees: Scenario C P a g e | 66 Department of Computer Science & Engineering GEC .II B.

P a g e | 67 Department of Computer Science & Engineering GEC .Tech Data Stractures Deletion: Problem Scenario 1: Depending on the original height of T2. Figure 7: Deletion in AVL trees: Scenario 1 There is a scenario symmetric to this.II B. the height of the tree will be either unchanged (height of T2 = h) or gets reduced (if height of T2 = h .1). See Figure 7.

II B.Tech Data Stractures Deletion: Problem Scenario 2: See Figure 8. Figure 8: Deletion in AVL trees: Scenario 2 P a g e | 68 Department of Computer Science & Engineering GEC . As usual. there is a symmetric scenario.