Вы находитесь на странице: 1из 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

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

6 7

48 50 GEC

II B.Tech

Data Stractures

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 Dijkstras algorithm b) Write a C program to find the minimum spanning tree using Warshalls 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.Tech

Data Stractures

4.stop Algorithm fib 1.start 2.if n=0 or 1 then return n 3.else return fib(n-1)+fib(n-2) 4. Stop.

Page |4

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Exercise 2:
a). 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. In general, recursive procedures need a terminating condition (otherwise they will run forever) and a recursive step (describing how the computation should proceed). We will use one of MzScheme's procedures trace to illustrate the behavior of recursive procedures. The procedure trace shows the intermediate steps as the recursion proceeds as well as the intermediate values returned. For example, let us define a procedure for counting the factorial of a number. We know that equals 1 and we will use this as our terminating condition. Apart from that, we know that is the same as , which gives us our recursive step. We are now ready to define the procedure itself: (define fact (lambda (n) (if (= n 0) ; the terminating condition 1 ; returning 1 (* n (fact (- n 1)))))) ; 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

II B.Tech

Data Stractures

ALGORITHM :
1. Start. 2. Get the number n to which Fcatorial value is to be generated. 3. Call to the function fact. 4.Stop Algorithm fact 1.Start 2.if n=0 or 1 then return 1 3.Else return n*fact(n-1) 4.Stop

Page |6

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

b). Write recursive C program for calculation of GCD (n, m)

ALGORITHM : The GCD algorithm:


Given m,n find gcd(m,n) We proved in class that the gcd can be found by repeatedly applying the division algorithm: a = bq + r. We start with a=m, b=n. The next pair is (b,r) [the quotient is not needed here]. We continue replacing a by the divisor and b by the remainder until we get a remainder 0. The last non-zero remainder is the gcd. 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,B4) 5 =B4 =C4 =MOD (A5,B5) 6 =B5 =C5 =MOD (A6,B6) 7 =B6 =C6 =MOD (A7,B7) 8 =B7 =C7 =MOD (A8,B8) 9 =B8 =C8 =MOD (A9,B9) 10 =B9 =C9 =MOD (A10,B10) 11 =B10 =C10 =MOD (A11,B11) 12 =B11 =C11 =MOD (A12,B12) 13 =B12 =C12 =MOD (A13,B13) 14 =B13 =C13 =MOD (A14,B14) Once row 5 is entered, it is copied to all lower rows. The spreadsheet automatically updates the formulas (that is what spreadsheets do!). A new pair of numbers can be entered in A2 and B2. Note that when a zero remainder occurs, the spreadsheet gives an error message on the following line. Page |7 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

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. DESCRIPTION:

How to solve the Towers of Hanoi puzzle


The Classical Towers of Hanoi - an initial position of all disks is on post 'A'.

Fig. 1 The solution of the puzzle is to build the tower on post 'C'.

Fig. 2 The Arbitrary Towers of Hanoi - at start, disks can be in any position provided that a bigger disk is never on top of the smaller one (see Fig. 3). At the end, disks should be in another arbitrary position. * )

Fig. 3

Solving the Tower of Hanoi


Page |8 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

'Solution' shortest path


Recursive Solution:
1. Identify biggest discrepancy (=disk N) 2. If moveable to goal peg Then move Else 3. Subgoal: set-up (N1)-disk tower on non-goal peg.

4. Go to 1. ...

Solving the Tower of Hanoi - 'regular' to 'perfect'


Let's start thinking how to solve it. Let's, for the sake of clarity, assume that our goal is to set a 4 disk-high tower on peg 'C' - just like in the classical Towers of Hanoi (see Fig. 2). Let's assume we 'know' how to move a 'perfect' 3 disk-high tower. Then on the way of solving there is one special setup. Disk 4 is on peg 'A' and the 3 disk-high tower is on peg 'B' and target peg 'C' is empty.

Fig. 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'. So think back. Forget the disks bigger than 3. Disk 3 is on peg 'C'. We need disk 3 on peg 'B'. To obtain that, we need disk 3 in place where it is now, 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

II B.Tech

Data Stractures

peg 'A'.

Fig. 5 Forget for the moment disk 3 (see Fig. 6). To be able to put disk 2 on peg 'A' we need to empty peg 'A' (above the thin blue line), disks smaller than disk 2 stacked on peg 'B'. So, our goal now is to put disk 1 on peg 'B'. As we can see, this is an easy task because disk 1 has no disk above it and peg 'B' is free.

Fig. 6 So let's move it.

Fig. 7 The steps above are made by the algorithm implemented in Towers of Hanoi when one clicks the "Help me" button. This button-function makes analysis of the current position and generates only one single move which leads to the solution. It is by design. When the 'Help me' button is clicked again, the algorithm repeats all steps of the analysis starting from the position of the biggest disk - in this example disk 4 - and generates the

P a g e | 10

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

next move - disk 2 from peg 'C' to peg 'A'.


/*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, that is to remember previous steps of the analysis and not to repeat the analysis of the Towers from the ground.

P a g e | 11

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Exercise 3:
a). 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, a binary search may be done. Variables Lb and Ub keep track of the lower bound and upper bound of the array, respectively. We begin by examining the middle element of the array. If the key we are searching for is less than the middle element, then it must reside in the top half of the array. Thus, we set Ub to (M 1). This restricts our next iteration through the loop to the top half of the array. In this way, each iteration halves the size of the array to be searched. For example, the first iteration will leave 3 items to test. After the second iteration, there will be one item left to test. Therefore it takes only three iterations to find any number. This is a powerful method. Given an array of 1023 elements, we can narrow the search to 511 elements in one comparison. After another comparison, and were looking at only 255 elements. In fact, we can search the entire array in only 10 comparisons. In addition to searching, we may wish to insert or delete entries. Unfortunately, an array is not a good arrangement for these operations. For example, to insert the number 18, we would need to shift A[3]A[6] down by one slot. Then we could copy number 18 into A[3]. A similar problem arises when deleting numbers. To improve the efficiency of insert and delete operations, linked lists may be used.

ALGORITHM :
Linear Search ( ): Description: Here A is an array having N elements. ITEM is the value to be searched. 1. Repeat for J = 1 to N 2. If (ITEM == A [J]) Then 3. Print: ITEM found at location J

P a g e | 12

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

4. Return [End of If] [End of For Loop] 5. If (J > N) Then 6. Print: ITEM doesnt exist [End of If] 7. Exit

P a g e | 13

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

b).Write C programs that use both recursive and non recursive functions to perform Binary search for a Key value in a given list.

ALGORITHM :
Binary Search ( ): Description: Here A is a sorted array having N elements. ITEM is the value to be searched. BEG denotes first element and END denotes last element in the array. MID denotes the middle value. 1. Set BEG = 1 and END = N 2. Set MID = (BEG + END) / 2 3. Repeat While (BEG <= END) and (A[MID] ? ITEM) 4. If (ITEM < A[MID]) Then 5. Set END = MID 1 6. Else 7. Set BEG = MID + 1 [End of If] 8. Set MID = (BEG + END) / 2 [End of While Loop] 9. If (A[MID] == ITEM) Then 10. Print: ITEM exists at location MID 11. Else 12. Print: ITEM doesnt exist [End of If] 13. Exit

P a g e | 14

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

c).Write C programs that use both recursive and non recursive functions to perform Fibonacci search for a Key value in a given list.

ALGORITHM :
Let Fk represent the k-th Fibonacci number where Fk+2=Fk+1 + Fk for k>=0 and F0 = 0, F1 = 1. To test whether an item is in a list of n = F m ordered numbers, proceed as follows: 1. Set k = m. 2. If k = 0, finish - no match. 3. Test item against entry in position Fk-1. 4. If match, finish. 5. If item is less than entry Fk-1, discard entries from positions Fk-1 + 1 to n. Set k = k - 1 and go to 2. 6. If item is greater than entry Fk-1, discard entries from positions 1 to Fk-1. Renumber remaining entries from 1 to Fk-2, set k = k - 2 and go to 2. If n is not a Fibonacci number, then let Fm be the smallest such number >n, augment the original array with Fm-n numbers larger than the sought item and apply the above algorithm for n'=Fm.

P a g e | 15

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Exercise 4:
a).Write C programs that implement Bubble sort, 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

II B.Tech

Data Stractures

b).Write C programs that implement Quick sort, 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

II B.Tech

Data Stractures

c).Write C programs that implement Insertion sort, 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. step3: now take three elements from the list and sort them as follows Step4::reapeat step 2 to 3 until the list is sorted.

P a g e | 18

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Exercise 5:
a). Write C programs that implement Heap sort, to sort a given list of integers in ascending order

Heap Sort Technique:

Heap sort algorithm, as the name suggests, is based on the concept of heaps. It begins by constructing a special type of binary tree, called heap, out of the set of data which is to be sorted. Note: A Heap by definition is a special type of binary tree in which each node is greater than any of its descendants. It is a complete binary tree. A semi-heap is a binary tree in which all the nodes except the root possess the heap property. If N be the number of a node, then its left child is 2*N and the right child 2*N+1. The root node of a Heap, by definition, is the maximum of all the elements in the set of data, constituting the binary tree. 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. Elementary implementations usually employ two arrays, one for the heap and the other to store the sorted data. But it is possible to use the same array to heap the unordered list and compile the sorted list. 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. Significance of a semi-heap - A Semi-Heap as mentioned above is a Heap except that the root does not possess the property of a heap node. This type of a heap is significant in the discussion of Heap Sorting, since after each "Heaping" of the set of data, the root is extracted and replaced by an element from the list. This leaves us with a Semi-Heap. 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. The following C function takes care of reheaping a set of data or a part of it. P a g e | 19 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

void downHeap(int a[], int root, int bottom) { int maxchild, temp, child; while (root*2 < bottom) { child = root * 2 + 1; if (child == bottom) { maxchild = child; } else { if (a[child] > a[child + 1]) maxchild = child; else maxchild = child + 1; } if (a[root] < a[maxchild]) { temp = a[root]; a[root] = a[maxchild]; a[maxchild] = temp; } else return; root = maxchild; } }

In the above function, both root and bottom are indices into the array. Note that, theoritically speaking, we generally express the indices of the nodes starting from 1 through size of the array. But in C, we know that array indexing begins at 0; and so the left child is
child = root * 2 + 1 /* so, for eg., if root = 0, child = 1 (not 0) */

In the function, what basically happens is that, starting from root each loop performs a check for the heap property of root and does whatever necessary to make it conform to it. If it does already conform to it, the loop breaks and the function returns to caller. Note that the function assumes that the tree constituted by the root and all its descendants is a Semi-Heap. Now that we have a downheaper, what we need is the actual sorting routine.
void heapsort(int a[], int array_size) { int i; for (i = (array_size/2 -1); i >= 0; --i) { downHeap(a, i, array_size-1);

P a g e | 20

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

} for (i = array_size-1; i >= 0; --i) { int temp; temp = a[i]; a[i] = a[0]; a[0] = temp; downHeap(a, 0, i-1); } }

Note that, before the actual sorting of data takes place, 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.
for (i = (array_size/2 -1); i >= 0; --i) { downHeap(a, i, array_size-1); }

Following this is the loop which actually performs the extraction of the root and creating the sorted list. Notice the swapping of the ith element with the root followed by a reheaping of the list.
for (i = array_size-1; i >= 0; --i) { int temp; temp = a[i]; a[i] = a[0]; a[0] = temp; downHeap(a, 0, i-1); }

The following are some snapshots of the array during the sorting process. The unodered list 8 6 10 3 1 2 5 4 After the initial heaping done by the first for loop. 10 6 8 4 1 2 5 3 Second loop which extracts root and reheaps. 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

II B.Tech

Data Stractures

b).Write C programs that implement Radix sort, 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. An example Assume that we have n integers in the range (0,n2) to be sorted. (For a bin sort, m = n2, and we would have an O(n+m) = O(n2) algorithm.) Sort them in two phases: 1. Using n bins, place ai into bin ai mod n, 2. Repeat the process using n bins, placing ai into bin floor(ai/n), being careful to append to the end of each bin. This results in a sorted list.
As an example, 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). After the first phase, 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, we placed each item in a bin indexed by the least significant decimal digit. Repeating the process, 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, we used the leading decimal digit to allocate items to bins, being careful to add each item to the end of the bin. We can apply this process to numbers of any size expressed to any suitable base or radix.

Generalized Radix Sorting:

P a g e | 22

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

We can further observe that it's not necessary to use the same radix in each phase, suppose that the sorting key is a sequence of fields, each with bounded ranges, eg the key is a date using the structure:

typedef struct t_date { int day; int month; int year; } date; If the ranges for day and month are limited in the obvious way, and the range for year is suitably constrained, eg 1900 < year <= 2000, then we can apply the same procedure except that we'll employ a different number of bins in each phase. In all cases, we'll sort first using the least significant "digit" (where "digit" here means a field with a limited range), then using the next significant "digit", placing each item after all the items already in the bin, and so on.
Assume that the key of the item to be sorted has k fields, fi|i=0..k-1, and that each fi has si discrete values, then a generalised radix sort procedure can be written:

radixsort( A, n ) { for(i=0;i<k;i++) { for(j=0;j<si;j++) bin[j] = EMPTY; for(j=0;j<n;j++) { move Ai to the end of bin[Ai->fi] } for(j=0;j<si;j++) concatenate bin[j] onto the end of A; } }

O(si)

O(n)

O(si)

Total

P a g e | 23

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Now if, for example, the keys are integers in (0,bk-1), for some constant k, then the keys can be viewed as k-digit base-b integers. Thus, si = b for all i and the time complexity becomes O(n+kb) or O(n). This result depends on k being constant. If k is allowed to increase with n, then we have a different picture. For example, it takes log2n binary digits to represent an integer <n. If the key length were allowed to increase with n, so that k = logn, then we would have:

. Another way of looking at this is to note that if the range of the key is restricted to (0, bk-1), then we will be able to use the radix sort approach effectively if we allow duplicate keys when n>bk. However, if we need to have unique keys, then k must increase to at least logbn. Thus, as n increases, we need to have logn phases, each taking O(n) time, and the radix sort is the same as quick sort!

P a g e | 24

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

c).Write C programs that implement Merge sort, to sort a given list of integers in ascending order

Algorithm to Sort an Array using MERGE SORT Merge Sort ( A, BEG, END ): Description: Here A is an unsorted array. BEG is the lower bound and END is the upper bound. 1. If (BEG < END) Then 2. Set MID = (BEG + END) / 2 3. Call Merge Sort (A, BEG, MID) 4. Call Merge Sort (A, MID + 1, END) 5. Call Merge Array (A, BEG, MID, END) [End of If] 6. Exit

Merge Array ( A, BEG, MID, END ) Description: Here A is an unsorted array. BEG is the lower bound, END is the upper bound and MID is the middle value of array. B is an empty array. 1. Repeat For I = BEG to END 2. Set B[I] = A[I] [Assign array A to B] [End of For Loop] 3. Set I = BEG, J = MID + 1, K = BEG 4. Repeat While (I <= MID) and (J <= END) 5. If (B[I] <= B[J]) Then [Assign smaller value to A] 6. Set A[K] = B[I] 7. Set I = I + 1 and K = K + 1 8. Else 9. Set A[K] = B[J] 10. 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

II B.Tech

Data Stractures

11. If (I <= MID) Then [Check whether first half 12. Repeat While (I <= MID) has exhausted or not] 13. Set A[K] = B[I] 14. Set I = I + 1 and K = K + 1 [End of While Loop] 15. Else 16. Repeat While (J <= END) 17. Set A[K] = B[J] 18. Set J = J + 1 and K = K + 1 [End of While Loop] [End of If] 19. Exit

P a g e | 26

Department of Computer Science & Engineering

GEC

II B.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. TOP points to the top most element and ITEM is the value to be inserted. 1. If (TOP == MAX) Then [Check for overflow] 2. Print: Overflow 3. Else 4. Set TOP = TOP + 1 [Increment TOP by 1] 5. Set STACK[TOP] = ITEM [Assign ITEM to top of STACK] 6. Print: ITEM inserted [End of If] 7. Exit Algorithm to Pop Item from Stack Pop ( ): Description: Here STACK is an array with MAX locations. TOP points to the top most element. 1. If (TOP == 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM] 5. Set TOP = TOP - 1 [Decrement TOP by 1] 6. Print: ITEM deleted [End of If] 7. Exit

P a g e | 27

Department of Computer Science & Engineering

GEC

II B.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. TOP points to the top most element and ITEM is the value to be inserted. 1. If (TOP == MAX) Then [Check for overflow] 2. Print: Overflow 3. Else 4. Set TOP = TOP + 1 [Increment TOP by 1] 5. Set STACK[TOP] = ITEM [Assign ITEM to top of STACK] 6. Print: ITEM inserted [End of If] 7. Exit Algorithm to Pop Item from Stack Pop ( ): Description: Here STACK is an array with MAX locations. TOP points to the top most element. 1. If (TOP == 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM] 5. Set TOP = TOP - 1 [Decrement TOP by 1] 6. Print: ITEM deleted [End of If] 7. Exit

P a g e | 28

Department of Computer Science & Engineering

GEC

II B.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.
1. Push ( left parenthesis onto stack. 2. Add ) right parenthesis to the end of expression I.

3. Scan I from left to right and repeat step 4 for each element of I a. until the stack becomes empty. 4. If the scanned element is: (i) an operand then add it to P. (ii) a left parenthesis then push it onto stack. (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. (vii) (ii) Add newly scanned operator to stack. (viii) a right parenthesis then: b. Pop from stack and add to P each operator (i) until a left parenthesis is encountered. c. Remove the left parenthesis. (i) (ii) 5. Exit. [End of Step 4 If] [End of step 3 For Loop]

P a g e | 29

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Algorithm to Evaluate Postfix Expression using Stack Evaluate ( ): Description: Here P is a postfix expression and this algorithm evaluates it. 1) Add a ) right parenthesis at the end of P. 2) Scan P from left to right and repeat steps 3 & 4 for each element i) of P until ) is encountered. 3) If an operand is encountered, push it onto stack. 4) If an operator ? is encountered then:

i) ii) iii) iv) v) vi)

Pop the top two elements from stack, where A is the top element and B is the next to top element. Evaluate B ? A. Place the result of (b) back on stack. [End of Step 4 If] [End of step 2 For Loop]

5) Set VALUE equal to the top element on the stack. 6) Exit.

P a g e | 30

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

b). Write C programs that implement Queue (its operations) using arrays. Algorithm to Insert Item into Queue Insert ( ): Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. ITEM is the value to be inserted. 1. If (REAR == N) Then [Check for overflow] 2. Print: Overflow 3. Else 4. If (FRONT and REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1 (b) Set REAR = 1 5. Else 6. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 7. QUEUE[REAR] = ITEM 8. Print: ITEM inserted [End of Step 1 If] 9. Exit

Algorithm to Delete Item from Queue Delete ( ): Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. 1. If (FRONT == 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. ITEM = QUEUE[FRONT] 5. 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

II B.Tech

Data Stractures

6. Else 7. Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If] 8. Print: ITEM deleted [End of Step 1 If] 9. Exit

P a g e | 32

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

c).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. FRONT and REAR points to the front and rear of the QUEUE. ITEM is the value to be inserted. 1. If (REAR == N) Then [Check for overflow] 2. Print: Overflow 3. Else 4. If (FRONT and REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1 (b) Set REAR = 1 5. Else 6. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 7. QUEUE[REAR] = ITEM 8. Print: ITEM inserted [End of Step 1 If] 9. Exit Algorithm to Delete Item from Queue Delete ( ): Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. 1. If (FRONT == 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. ITEM = QUEUE[FRONT] 5. If (FRONT == REAR) Then [Check if only one element is left] P a g e | 33 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

(a) Set FRONT = 0 (b) Set REAR = 0 6. Else 7. Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If] 8. Print: ITEM deleted [End of Step 1 If] 9. Exit

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

P a g e | 34

Department of Computer Science & Engineering

GEC

II B.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. PTR will point to the current node and PREV will point to the previous node. REV will maintain the reverse list.

1. Set PTR = START, PREV = NULL 2. Repeat While (PTR!= NULL) 3. REV = PREV 4. PREV = PTR 5. PTR = PTR->LINK 6. PREV->LINK = REV [End of While Loop] 7. 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 is a pointer variable which will contain address of new node. N is the value after which new node is to be inserted and ITEM is the value to be inserted. 1. If (START == NULL) Then 2. Print: Linked-List is empty. It must have at least one node 3. Else 4. Set PTR = START, NEW = START 5. Repeat While (PTR != NULL) P a g e | 35 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

6. If (PTR->INFO == N) Then 7. NEW = New Node 8. NEW->INFO = ITEM 9. NEW->LINK = PTR->LINK 10. PTR->LINK = NEW 11. Print: ITEM inserted 12. ELSE 13. PTR = PTR->LINK

P a g e | 36

Department of Computer Science & Engineering

GEC

II B.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. PREV is a pointer variable which contains address of previous node. ITEM is the value to be inserted.

1. If (START == NULL) Then [Check whether list is empty] 2. START = New Node [Create a new node] 3. START->INFO = ITEM [Assign ITEM to INFO field] 4. START->LINK = NULL [Assign NULL to LINK field] 5. Else 6. If (ITEM < START->INFO) Then [Check whether ITEM is less then value in first node] 7. PTR = START 8. START = New Node 9. START->INFO = ITEM 10. START->LINK = PTR 11. Else 12. Set PTR = START, PREV = START 13. Repeat While (PTR != NULL) 14. If (ITEM < PTR->INFO) Then 15. PREV->LINK = New Node 16. PREV = PREV->LINK 17. PREV->INFO = ITEM 18. PREV->LINK = PTR 19. Return 20. Else If (PTR->LINK == NULL) Then [Check whether PTR reaches last node] 21. PTR->LINK = New Node P a g e | 37 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

22. PTR = PTR->LINK 23. PTR->INFO = ITEM 24. PTR->LINK = NULL 25. Return 26. Else 27. PREV = PTR 28. PTR = PTR->LINK [End of Step 14 If] [End of While Loop] [End of Step 6 If] [End of Step 1 If] 29. Exit

P a g e | 38

Department of Computer Science & Engineering

GEC

II B.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. PTR is a pointer variable which contains address of node to be deleted. PREV is a pointer variable which points to previous node. ITEM is the value to be deleted.

1. If (START == NULL) Then [Check whether list is empty] 2. Print: Linked-List is empty. 3. Else 4. PTR = START, PREV = START 5. Repeat While (PTR->LINK != NULL) 6. PREV = PTR [Assign PTR to PREV] 7. PTR = PTR->LINK [Move PTR to next node] [End of While Loop] 8. ITEM = PTR->INFO [Assign INFO of last node to ITEM] 9. If (START->LINK == NULL) Then [If only one node is left] 10. START = NULL [Assign NULL to START] 11. Else 9. PREV->LINK = NULL [Assign NULL to link field of second last node] [End of Step 9 If] 10. Delete PTR 11. Print: ITEM deleted [End of Step 1 If] 12. Exit

P a g e | 39

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Exercise 9:
d) Adding two large integers which are represented in linked list fashion.

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. This algorithm adds these two arrays.

1. If (M ? X) or (N ? Y) Then 2. Print: Addition is not possible. 3. Exit [End of If] 4. Repeat For I = 1 to M 5. Repeat For J = 1 to N 6. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7. Exit Explanation: First, 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. if they are not equal, then addition is not possible and the algorithm exits. But if they are equal, then first for loop iterates to the total number of rows i.e. M and the second for loop iterates to the total number of columns i.e. N. In step 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

II B.Tech

Data Stractures

e)

Write a C program to reverse elements of a Single linked list.

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. REV will maintain the reverse list.

1. Set PTR = START, PREV = NULL 2. Repeat While (PTR != NULL) 3. REV = PREV 4. PREV = PTR 5. PTR = PTR->LINK 6. PREV->LINK = REV [End of While Loop] 7. START = PREV 8. Exit

P a g e | 41

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

f)

Write a C program to representation the given Sparse matrix using arrays.

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. This algorithm adds these two arrays. 1. If (M ? X) or (N ? Y) Then 2. Print: Addition is not possible. 3. Exit [End of If] 4. Repeat For I = 1 to M 5. Repeat For J = 1 to N 6. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7. Exit Explanation: First, 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. if they are not equal, then addition is not possible and the algorithm exits. But if they are equal, then first for loop iterates to the total number of rows i.e. M and the second for loop iterates to the total number of columns i.e. N. In step 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 | 42

Department of Computer Science & Engineering

GEC

II B.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. This algorithm multiplies these two arrays. 1. If (M ? Y) or (N ? X) Then 2. Print: Multiplication is not possible. 3. Else 4. Repeat For I = 1 to N 5. Repeat For J = 1 to X 6. Set C[I][J] = 0 7. Repeat For K = 1 to Y 8. 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. 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. If they are not equal, then multiplication is not possible. But, if they are equal, the first for loop iterates to total number of columns of A i.e. N and the second for loop iterates to the total number of rows of B i.e. X. In step 6, all the elements of C are set to zero. Then the third for loop iterates to total number of columns of B i.e. Y. In step 8, 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

II B.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, i.e.,there is no node with degree greater than two. For binary trees we distinguish between the subtree on the left and on the right, whereas for trees the order of the subtree was irrelevant. Also a binary tree may have zero nodes. Thus a binary tree is really a different object than a tree. 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. We can define the data structure binary tree as follows: structure BTREE declare CREATE( ) --> btree ISMTBT(btree,item,btree) --> boolean MAKEBT(btree,item,btree) --> btree LCHILD(btree) --> btree DATA(btree) --> item RCHILD(btree) --> btree for all p,r in btree, d in item let ISMTBT(CREATE)::=true ISMTBT(MAKEBT(p,d,r))::=false LCHILD(MAKEBT(p,d,r))::=p; LCHILD(CREATE)::=error DATA(MAKEBT(p,d,r))::d; DATA(CREATE)::=error RCHILD(MAKEBT(p,d,r))::=r; RCHILD(CREATE)::=error end end BTREE

P a g e | 44

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

b) Write a recursive C program, for Traversing a binary tree in preorder, inorder and postorder.

ALGORITHM:
PREORDER The first type of traversal is pre-order whose code looks like the following: sub P(TreeNode) Output(TreeNode.value) If LeftPointer(TreeNode) != NULL Then P(TreeNode.LeftNode) If RightPointer(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, A, D, C, E, G, I, 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.LeftNode) Output(TreeNode.value) If RightPointer(TreeNode) != NULL Then P(TreeNode.RightNode) end sub P a g e | 45 Department of Computer Science & Engineering GEC

II B.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, C, D, E, F, G, H, 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.LeftNode) If RightPointer(TreeNode) != NULL Then P(TreeNode.RightNode) Output(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, C, E, D, B, H, I, G, F

P a g e | 46

Department of Computer Science & Engineering

GEC

II B.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. root the root of a new binary search tree named T; index 1; while index N do

InsertBST (A[index ], root); index index + 1; end while return T Algorithm InOrder (root) Perform an inorder (second-visit) traversal of the BST with root named root. if root is empty then return else InOrder (left child of root); output the value in root; InOrder (right child of root); end if

Algorithm TreeSort (A) Sort the elements in array A using a binary search tree (BST). CreateBST (A); {Creates a new BST T containing the elements of A} InOrder (root of T); {Sorts the elements in T using an inorder traversal}

b)

Write a C program

to insert a note into a BST.

Binary Search Tree Algorithms Algorithm Insert BST (v, root) Iteratively insert a value v into a binary search tree (BST) with root named root. P a g e | 47 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

if root is empty then root v; else node root; loop {an infinite loop; 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; else insert v as the left child of node; exit the loop; end if else if the right child of node exists then node right child of node; else insert v as the right child of node; exit the loop; end if end if end loop end if Algorithm InsertBST (v, root) Recursively insert a value v into a binary search tree (BST) with root named root. if root is empty then root v; else if v value stored in root then

if the left child of root exists then InsertBST (v, left child of root); else insert v as the left child of root; P a g e | 48 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

end if else if the right child of root exists then InsertBST (v, right child of root); else insert v as the right child of root; end if end if end if

c)

Write a C program

to delete a note from a BST.

DELETION ALGORITHM 1) Check for the cases that the delete operation fails: a. IF <root> == NULL (tree is empty) b. Search the BST for the element to be deleted; IF <element> is not found (there is no such element in the tree). // In both cases a&b the delete operation fails. 2) IF <element> is found, then the delete operation has four cases: case 1: The <node> to be deleted has no <left> and <right> subtrees; that is, the <node> to be deleted is a leaf. // the easiest case case 2: The <node> to be deleted has no <left> subtree; that is, the <left> subtree is empty. but it has nonempty <right> subtree. case 3: The <node> to be deleted has no <right> subtree; that is, the <right> subtree is empty. but it has nonempty <left> subtree. case 4: The <node> to be deleted has nonempty <left> and <right> subtrees; that is, the <node> to be deleted has <left> and <right> subtrees. // the hardest case

P a g e | 49

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Exercise 12:
a) Write a C program algorithm to compute the shortest path of a graph using Dijkstras

To implement Dijkstras Algorithm DESCRIPTION: Shortest path from a specified vertex S to another specified vertex T can be stated as follows: A simple weighted Graph Gof 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, d ij >=0 D ij=0 D ij=, 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 Disjkstras Alogrithm is the most efficient shortest path Alo grithm

P a g e | 50

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

EXAMPLE: Finding the shortest path from vertex B to G:

Starting vertex B is labeled 0. All successor of B get labeled. Smallest label become permanent Successor of C gets labeled. 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.

P a g e | 51

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

b) Write a C program to find the minimum spanning tree using Warshalls Algorithm

ALGORITHM:
Warshall algorithm is a dynamic programming formulation, to solve the all-pairs shortest path problem on directed graphs. It finds shortest path between all nodes in a graph. If finds only the lengths not the path. 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. Algorithm: Input Format: Graph is directed and weighted. 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. 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. size[maxVertices] is initialed to{0}, represents the size of every vertex i.e. the number of edges corresponding to the vertex. visited[maxVertices]={0} represents the vertex that have been visited. distance[maxVertices][maxVertices] represents the weight of the edge between the two vertices or distance between two vertices. Initialize the distance between two vertices using init() function. init() function- It takes the distance matrix as an argument. 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.Tech

Data Stractures

iter + 1 Where, INF is a very large integer value. Initialize and input the graph. Call Floyd Warshall function. It takes the distance matrix (distance[maxVertices][maxVertices]) and number of vertices as argument (vertices). Initialize integer type from, to, 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],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. 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. Output the distance between every two vertices.

P a g e | 53

Department of Computer Science & Engineering

GEC

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

II B.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, since all the characters are scanned, the remaining element in the stack (there will be only one element in the stack) will be returned. End result : Postfix String : 123*+4Result : 3

P a g e | 57

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

3. Write a C program search the elements using Breadth First Search Algorithm & Depth First Search Algorithm

DESCRIPTION: 1. A graph can be thought of a collection of vertices (V) and edges (E), so we write, G = (V, E) 2. Graphs can be directed, or undirected, weighted or unweighted. 3. A directed graph, or digraph, is a graph where the edge set is an ordered pair. That is, edge 1 being connected to edge 2 does not imply that edge 2 is connected to edge 1. (i.e. it has direction trees are special kinds of directed graphs). 4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1 being connected to edge 2 does imply that edge 2 is connected to edge 1. 5. A weighted graph is graph which has a value associated with each edge. This can be a distance, or cost, or some other numeric value associated with the edge. 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. At this time of exploration of the new vertex u begins. When this new vertex has been explored, the exploration of v continues. The search terminates when all reached vertices have been fully explored. The search process is best described recursively in the following algorithm. Algorithm DFS(v) // Given an undirected(directed) graph G=(V,E) with n vertices and an //array visited [] initially set to zero, this algorithm visits all vertices reachable //from v. G and visited[] are global. { visited[v]:=1; for each vertex w adjacent from v do { if (visited[w]=0) then DFS(w); } P a g e | 58 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

DESCRIPTION: 1. A graph can be thought of a collection of vertices (V) and edges (E), so we write, G = (V, E) 2. Graphs can be directed, or undirected, weighted or unweighted. 3. A directed graph, or digraph, is a graph where the edge set is an ordered pair. That is, edge 1 being connected to edge 2 does not imply that edge 2 is connected to edge 1. (i.e. it has direction trees are special kinds of directed graphs). 4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1 being connected to edge 2 does imply that edge 2 is connected to edge 1. 5. A weighted graph is graph which has a value associated with each edge. This can be a distance, or cost, or some other numeric value associated with the 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. A vertex is said to have been explored by an algorithm when the algorithm has visited all vertices adjacent from it. All unvisited vertices adjacent from v are visited next. These are new unexplored vertices. Vertex v has now been explored. The newly visited vertices have not been explored and or put on to the end of a list of unexplored list of vertices. The first vertex on this list is the next to be explored. Exploration continues until no unexplored vertex is left. The list of unexplored vertices operates as a queue and can be represented using any of the standard queue representations.

Algorithm BFS(v) //A breadth first search of G is carried out beginning at vertex v. For //any node I, visited[I=1 if I has already been visited. The graph G //and array visited are global; visited[] is initialized to zero. { u:=v; //q is a queue of unexplored vertices visited[v]:=1; repeat { for all vertices w adjacent from u do P a g e | 59 Department of Computer Science & Engineering GEC

II B.Tech

Data Stractures

{ if (visited[w]=0) then { add w to q; //w is unexplored visited[w]:=1; } } if q is empty then return; //no unexplored vertex delete u from q; //get first unexplored vertex }until(false); } Algorithm BFT(G, 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); }

P a g e | 60

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

4. Write a C program to perform various operations i.e., insertions and deletions on AVL trees AVL Trees: Also called as: Height Balanced Binary Search Trees. Search, Insertion, and Deletion can be implemented in worst case O (log n) time.
Definition: An AVL tree is a binary search tree in which

1. The heights of the right subtree and left subtree of the root differ by at most 1 2. The left subtree and the right subtree are themselves AVL trees 3. 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.

P a g e | 61

Department of Computer Science & Engineering

GEC

II B.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, 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, having the minimum number of nodes. Fh can be visualized as in Figure 2. Let Fl and Fr be AVL trees which are the left subtree and right subtree, respectively, of Fh. Then Fl or Fr must have height h-2. Suppose Fl has height h-1 so that Fr has height h-2. Note that Fr has to be an AVL tree having the minimum number of nodes among all AVL trees with height of h-1. Similarly, Fr will have the minimum number of nodes among all AVL trees of height h--2. Thus we have | Fh| = | Fh - 1| + | Fh - 2| + 1 Where | Fr| denotes the number of nodes in Fr. Such trees are called Fibonacci trees. See Figure 3.

P a g e | 62

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Figure 3: Fibonacci trees

Note that | F0| = 1 and | F1| = 2. Adding 1 to both sides, we get | Fh| + 1 = (| Fh - 1| + 1) + (| Fh - 2| + 1) Thus the numbers | Fh| + 1 are Fibonacci numbers. Using the approximate formula for Fibonacci numbers, we get

| Fh | + 1
h 1.44log| Fn| The sparsest possible AVL tree with n nodes has height h 1.44log n

The worst case height of an AVL tree with n nodes is 1.44log n

Algorithm for Insertions and Deletions into an AVL Trees:


While inserting a new node or deleting an existing node, the resulting tree may violate the (stringent) AVL property. To reinstate the AVL property, we use rotations. See Figure 4.

P a g e | 63

Department of Computer Science & Engineering

GEC

II B.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. Left Rotation: Temp = p p temp p = temp ; Left rotation and right rotation preserve BST property Inorder ordering of keys

right ; left ;

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, not necessarily the root. Fixing the AVL property involves doing a series of single or double rotations. Double rotation involves a left rotation followed or preceded by a right rotation. In an AVL tree of height h, no more than [h/2] rotations are required to fix the AVL property.

P a g e | 64

Department of Computer Science & Engineering

GEC

II B.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.Tech

Data Stractures

Insertion: Problem Scenario 2: (Scenario C) Scenario B is symmetrical to this. See Figure 6.

Figure 6: Insertion in AVL trees: Scenario C

P a g e | 66

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Deletion: Problem Scenario 1:

Depending on the original height of T2, 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. Figure 7: Deletion in AVL trees: Scenario 1

There is a scenario symmetric to this.

P a g e | 67

Department of Computer Science & Engineering

GEC

II B.Tech

Data Stractures

Deletion: Problem Scenario 2: See Figure 8. As usual, there is a symmetric scenario.

Figure 8: Deletion in AVL trees: Scenario 2

P a g e | 68

Department of Computer Science & Engineering

GEC

Вам также может понравиться