Data Structures Through C Laboratory Manual II YEAR B.TECH (CSE, IT)

Department of Computer Science & Engineering

Data Structures Through C Laboratory Manual II YEAR B.TECH (CSE, IT)

Department of Computer Science & Engineering

Document No:

Date of Issue

Compiled by

30 JUNE 2012

B. Madhuravani

Authorized by

(Assistant Professor)

MLRIT/CSE/LAB MANUAL/DSC Date of Revision VERSION 1.1.3

JUNE 2013

Verified by Mr. Niladri

2|Page

HOD(CSE)

PREFACE

DS Through C is one of the important subjects included in the second year curriculum by JNTU, Hyderabad. In addition to theory subject also includes DS Through C as lab practical’s using C language. The DS Through C constitutes step-by-step procedure encompassing understanding of the problem, developing logic to solve the problem in the form of Algorithms and converting logic into source code using C language. The students must grasp three aspects while doing DS Through C in the lab as given below. a. Understanding grammar of C language to enable writing correct program from syntax point of view. b. Developing the logic to find solution to a given problem from semantic point of view. c. Importance of space and time complexity to enable writing a program which meets requirements of memory constraints and time constraints. Students will be in a position to grasp the above three aspects while doing lab practical’s as defined in the manual through four steps i.e design and code, compile, linkage and run and test. This manual is a collective effort of the faculty teaching second year DS Through C subject. This manual will need constant up gradation based on the student feedback and change in the syllabus.

HOD (IT)

3|Page

HOD (CSE)

DEAN

PRINCIPAL

Steps in Program Development Program development is a multi step process. The steps are 1) Understand the problem 2) Develop a solution 3) Write the program and test it. 1. Understand the problem: When you are assigned to develop a program for solving a problem, you are given the programming requirements. Study these requirements carefully resolve all doubts and ensure that you have understood it fully as per the user requirements. 2. Develop a solution: Once you have understood the problem, you have to develop the solution in terms of some programming language. The tools that help in this are: a) Algorithm / Pseudo code b) Flowchart c) Programming Language, like C etc., d) Test cases a) Algorithm Definition: A method of representing the step-by-step logical procedure for solving a problem in natural language (like English, etc.) is called as an Algorithm. Algorithm can also be defined as an ordered sequence of well-defined and effective operations that, when executed, will always produce a result and eventually terminate in a finite amount of time. On the whole an algorithm is a recipe for finding a right answer to a problem by breaking it down into simple steps. Properties an Algorithm should possess: a. Generality: The algorithm must be complete in itself so that it can also be used to solve all problems of a specific type for given input data. b. Input / Output: Each algorithm can take zero, one or more input data and must produce one or more output values. c. Optimization: Unnecessary steps should be eliminated so as to make the algorithm to terminate in finite number of steps. d. Effectiveness: Each step must be effective in the sense that it should be primitive (easily convertible into program statement) and can be performed exactly in a finite amount of time. e. Definiteness: Each step of the algorithm, should be precisely and unambiguously stated.

4|Page

b) Flowchart: Definition: It is a diagrammatic representation of an algorithm. It is constructed using different types of symbols. Standard symbols used in drawing flowcharts:

Oval

Parallelogram

Document

Rectangle

Diamond

Circle

Arrow

5|Page

Terminal

Input/output

Printout

Process

Decision

Connector

Flow

Start/stop/begin/end

Making data available for processing(input) or recording of the processed information(output) Show data output in the form of document

Any processing to be performed. A process changes or moves data. An assignment operation Decision or switching type of operation

Used to connect different parts of flowchart

Joins two symbols and also represents flow of execution

Bracket with broken line

Double sided rectangle

Annotation

Predefined process

Descriptive explanation

comments

Modules or subroutines specified elsewhere

Programming and Testing: A computer program is the sequence of instructions written in a computer language according to the algorithm and computer follows these in carrying out its computations. The process of writing a program is called programming. Steps involved in Computer Programming:      

Problem Understanding Problem Definition Program writing Error analysis Validation & Verification Documentation & Maintenance

6|Page

or

LAB CODE 1. Student should report to the concerned as per the time table. 2. Students who turn up late to the labs will in no case be permitted to the program schedule for the day. 3. After completion of the program, certification of the concerned staff in-charge in the observation book is necessary. 4. Student should bring a note book of 100 pages and should enter the readings/observations into the note book while performing the experiment. 5. The record of observations along with the detailed experimental Algorithm of the experiment in the immediate last session should be submitted and certified staff member in-charge 6. Not more than 3 students in a group are permitted to perform the experiment on the set. 7. The group-wise division made in the beginning should be adhered to and no mix up of students among different groups will be permitted. 8. The components required pertaining to the experiment should be collected from stores in-charge after duly filling in the requisition form. 9. When the experiment is completed, should disconnect the setup made by them, and should return all the components / instruments taken for the purpose. 10. Any damage of the equipment or burn –out components will be viewed seriously either by putting penalty or by dismissing the total group of students from the lab for the semester / year. 11. Students should be present in the labs for total scheduled duration. 12. Students are required to prepare thoroughly to perform the experiment before coming to laboratory. 13. Algorithm sheets/data sheets provided to student’s groups should be maintained neatly and to be returned after the experiment.

7|Page

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD II Year B.Tech. CSE - I Sem

L T/P/D 0 -/3/-

C 2

DATA STRUCTURES LAB Objectives: To write and execute programs in C to solve problems using data structures such as arrays, linked lists, stacks, queues, trees, graphs, hash tables and search trees. To write and execute write programs in C to implement various sorting and searching methods. Recommended Systems/Software Requirements:  Intel based desktop PC with minimum of 166 MHZ or faster processor with at least 64 MB RAM and 100MB free disk space.  C compiler. Week1: Write a C program that uses functions to perform the following: a) Create a singly linked list of integers. b) Delete a given integer from the above linked list. c) Display the contents of the above list after deletion. Week2: Write a C program that uses functions to perform the following: a) Create a doubly linked list of integers. b) Delete a given integer from the above doubly linked list. c) Display the contents of the above list after deletion. Week3: Write a C program that uses stack operations to convert a given infix expression into its postfix Equivalent, Implement the stack using an array. Week 4: Write C programs to implement a double ended queue ADT using i)array and ii)doubly linked list respectively. Week 5: Write a C program that uses functions to perform the following: a) Create a binary search tree of characters. b) Traverse the above Binary search tree recursively in Postorder. Week 6: Write a C program that uses functions to perform the following: a) Create a binary search tree of integers. b) Traverse the above Binary search tree non recursively in inorder. Week 7: Write C programs for implementing the following sorting methods to arrange a list of integers in Ascending order : a) Insertion sort b) Merge sort Week 8: Write C programs for implementing the following sorting methods to arrange a list of integers in ascending order: a) Quick sort b) Selection sort 8|Page

Week 9: i) Write a C program to perform the following operation: a)Insertion into a B-tree. ii) Write a C program for implementing Heap sort algorithm for sorting a given list of integers in ascending order. Week 10: Write a C program to implement all the functions of a dictionary (ADT) using hashing. Week 11: Write a C program for implementing Knuth-Morris- Pratt pattern matching algorithm. Week 12: Write C programs for implementing the following graph traversal algorithms: a)Depth first traversal b)Breadth first traversal TEXT BOOKS: 1. C and Data Structures, Third Edition, P.Padmanabham, BS Publications. 2. C and Data Structures, Prof. P.S.Deshpande and Prof. O.G. Kakde, Dreamtech Press. 3. Data structures using C, A.K.Sharma, 2nd edition, Pearson. 4. Data Structures using C, R.Thareja, Oxford University Press. 5. C and Data Structures, N.B.Venkateswarlu and E.V.Prasad,S.Chand. 6. C Programming and Data Structures, P.Radha Krishna, Hi-Tech Publishers.

9|Page

INDEX S.No 1 2

3

4

5

6

7

8

9

10

11 12 13

Experime Name of the Experiment nt No Objective , Outcomes, Hardware Software Requirements Write a C program that uses functions to perform the 1 following: a) Create a singly linked list of integers. b) Delete a given integer from the above linked list. c) Display the contents of the above list after deletion. Write a C program that uses functions to perform the 2 following: a) Create a doubly linked list of integers. b) Delete a given integer from the above doubly linked list. c) Display the contents of the above list after deletion Write a C program that uses stack operations to convert a 3 given infix expression into its postfix Equivalent, Implement the stack using an array. Write C programs to implement a double ended queue ADT 4 using i) Array ii) Doubly linked list respectively. Write a C program that uses functions to perform the 5 following: a) Create a binary search tree of characters. b) Traverse the above Binary search tree recursively in Postorder. Write a C program that uses functions to perform the 6 following: a) Create a binary search tree of integers. b) Traverse the above Binary search tree non recursively in Inorder. Write C programs for implementing the following sorting 7 methods to arrange a list of integers in Ascending order : a) Insertion sort b) Merge sort Write C programs for implementing the following sorting 8 methods to arrange a list of integers in ascending order: a) Quick sort b) Selection sort i) Write a C program to perform the following operation: 9 a)Insertion into a B-tree. ii) Write a C program for implementing Heap sort algorithm for sorting a given list of integers in ascending order. Write a C program to implement all the functions of a 10 dictionary (ADT) using hashing. Write a C program for implementing Knuth-Morris- Pratt 11 pattern matching algorithm. Write C programs for implementing the following graph 12 traversal algorithms: a)Depth first traversal b)Breadth first traversal

10 | P a g e

Page No

Objective  

To write and execute programs in C to solve problems using data structures such as arrays, linked lists, stacks, queues, trees, graphs, hash tables and search trees. To write and execute write programs in C to implement various sorting and searching methods.

Outcome   

Ability to identify the appropriate data structure for given problem. Graduate able to design and analyze the time and space complexity of algorithm or program. Ability to effectively use compilers includes library functions, debuggers and trouble shooting.

Hardware and Software required 1. 2. 3. 4. 5.

11 | P a g e

Intel based desktop PC Minimum of 166 MHZ or faster processor At least 64 MB RAM At least 100 MB free disk space C++ compiler and STL Recommended

Experiment No: 1 Experiment as given in the JNTUH curriculum. Week1: Write a C program that uses functions to perform the following: a) Create a singly linked list of integers. b) Delete a given integer from the above linked list. c) Display the contents of the above list after deletion AIM: To Implement singly linked list of integers in data structure using functions.

THEORY: Singly Linked List Generally a Linked List means "Singly Linked List". It is a chain of records known as Nodes. Each node has at least two members, one of which points to the next Node in the list and the other holds the data.

Figure 1: Singly Linked List Basically Single Linked Lists are uni-directional as they can only point to the next Node in the list but not to the previous. We use below structure for a Node in our example. struct Node { int Data; struct Node *Next; }; Variable Data holds the data in the Node (It can be a pointer variable pointing to the dynamically allocated memory) while Next holds the address to the next Node in the list.

Figure 2: Node in a Singly Linked List Head is a pointer variable of type struct Node which acts as the Head to the list. Initially we set 'Head' as NULL which means list is empty. Basic Operations on a Singly Linked List  Traversing a List  Inserting a Node in the List  Deleting a Node from the List .

12 | P a g e

Inserting a Node in Singly Linked List 1.Inserting a Node at the beginning of the List Inserting a Node at the End of the List Inserting a Node at position 'p' in the List Deletion of a Node from a Singly Linked List Deleting First Node in Singly Linked List Deleting Last Node in the Singly Linked List Deleting Node from position 'p' in the List

ALGORITHM: Initialize the first and last nodes with NULL values struct node *first=NULL,*last=NULL,*next,*prev,*cur; 1. Algorithm creating a new node: Step 1: if the list is empty then first==NULL Step 2: Create a new node cur=(struct node*) malloc (sizeof (struct node)); Step 3: Read the content of node Step 4: Assign new node link to NULL cur->link=NULL Step 5: Assign new node to first & last node first=cur last=cur Step 6: If the list is not empty call insert function insert () Step 7 : Stop 2. Algorithm for Inserting a new node: Step 1 : Initialize count c to 1 Step 2 : Create inserting node cur=(struct node*)malloc(sizeof (struct node)); Step 3: Read the content of node Step 4: Read the position of insertion Step 5: Inserting in first position Check if the pos=1 and first!=NULL cur->link=first; first=cur; Step 6: Inserting in a given position next=first; repeat the steps a to c until c < pos a. prev=next; b. next=prev->link; c. c++;

13 | P a g e

cur->link=prev->link; prev->link=cur; Step 7 : Stop 3. Algorithm for Deleting a node: Step 1 : Initialize count c to 1 Step 2 : Read the position for deletion Step 3 : Check if first=NULL print list is empty Step 4 : If the list contains single element Check if pos=1 and first->link=NULL print deleted element is first->data Step 5 : Assign first to NULL first=NULL; Step 6 : If the list contains more than one element and to delete first element if pos=1 and first->link!=NULL cur=first; first=first->link; cur->link=NULL; print deleted element is cur->data free(cur) Step 7 : If the list contains more than one element and to delete an element at given position next=first; repeat the steps a to c until c < pos a. cur=next; b. next=next->link; c. c++; cur->link=next->link; next->link=NULL; print deleted element is next->data free(next); Step 8 : Stop 4. Algorithm for Displaying a node: Step1 : Check if first node is NULL print list is empty Step2: If first node is not NULL then cur=first; repeat the steps a to b until cur!=NULL a . print cur->data b . cur=cur->link; Step3 : Stop

14 | P a g e

INPUT & OUTPUT Insert() : 1 2 3 4 5 Display () : 1->2->3->4->5 Delete() : 3 Display() : 1->2->4->5 PROBLEM DEFINITIONS DIFFERENT FROM JNTU TOPICS FOR WEEK1 P1: Write a C program that uses functions to perform the following: a) Create a singly linked list of even integers between 1 to 100. b) Delete the nodes which are divisible by 5 from the above linked list. c) Display the first five contents of the above list after deletion. Test Case 1: 12 10 15 Result : 12->10 Number not in range or not even Test Case 2: 10 12 24 34 40 44 66 68 Result: display: 10 12 24 34 40 44 66 68 delete: 10 40 display:12 24 34 44 66 68 P2: Write a C program that uses functions to perform the following: a) Create a singly linked list of odd integers between 1 to 50. b) Delete the nodes which are multiples of 3 from the above linked list. c) Display the last five contents of the above list after deletion. Test Case 1: 9 11 51 Result : 9->11 Number not in range or not odd Test Case 2: 9-->11-->13-->17-->19-->23-->25--> Result: display: 9-->11-->13-->17-->19-->23-->25--> deleted: 9 display: 25-> 23-> 19-> 17->13 P3: Write a C program that uses functions to perform the following: a) Create a singly linked list of prime integers between 10 to 100. b) Delete the nodes which are less than 30 from the above linked list. c) Display the nodes from the given position(read position). Test Case 1: 11->37>41>43>7 Result: 11->37>41>43> Number not in range or not prime

15 | P a g e

Test Case 2: 11->37>41>43 Delete: 37>41>43 Display: position 2 41->43 P4: Write a C program that uses functions to perform the following: a) Create a singly linked list of integers divisible by 5 between 100 to 1000. b) Delete the nodes which are greater than 500 from the above linked list. c) Display the nodes from the beginning of list to the given position(read position). Test Case 1: 600-->700-->500-->400-->300-->24 Result: 600-->700-->500-->400-->300 the number is not divisible by 5 or not in range Test Case 2: 600-->700-->500-->400-->300 Display :position 3 600-->700-->500 Deleted:600 700 P5: Write a C program that uses functions to perform the following: a) Create a singly linked list of integers which are multiple of 3 between 1 to 100. b) Delete the nodes which are multiple of 5 from the above linked list. c) Display the nodes between 50 to 100 from the above given list. Test Case 1: 9-->3-->6-->75-->15-->123 Result: the number is not multiple of 3 or not in range Test Case 2: 9-->3-->6-->75-->15-->123 Display:75-> Delete: 75 15 9-->3-->6 P6: Write a C program that uses functions to perform the following: a) Create a singly linked list of integers less than 100. b) Delete the nodes which are greater than 50 from the above linked list. c) Display the nodes between 75 to 100 from the above given list. Test Case 1: 45-->23-->56-->89-->99--> Result: 45-->23-->56-->89-->99--> 123 the number is not less than 100 Test Case 2: 45-->23-->56-->89-->99--> Display: 89-->99--> Delete: 56 89 99 45-->23 P7: Write a C program that uses functions to perform the following: a) Create a singly linked list of integers greater than 100. b) Delete the nodes which are less than 500 from the above linked list. c) Display the above given list in ascending order. Test Case 1: 600-->200-->300-->500-->600-->900-->90 Result: the number is not greater than 100 Test Case 2: 600-->200-->300-->500-->600-->900

16 | P a g e

Display: data in ascending order is 200 300 500 600 600 900 Delete: 200 300 600-->500-->600-->900 P8: Write a C program that uses functions to perform the following: a) Create a singly linked list of integers between 100 to 1000. b) Delete the nodes which are multiple of 10 from the above linked list. c) Display the nodes which are multiples of 3 from the above given list. Test Case 1: 345-->315-->310-->200-->100-->1000-->1001 Result: the number is not in range 100-1000 Test Case 2: 345-->315-->310-->200-->100-->1000 Display: 345-->315 Delete: 310 200 100 1000 345-->315 P9: Write a C program that uses functions to perform the following: a) Create a singly linked list of perfect integers between 1 to 1000. b) Delete a node from a given position(read position)from the above linked list. c) Display the above given list in reverse order. Test Case 1: 6-->28-->496-->455 Result: the number is not in range 1-1000 or not perfect number Test Case 2: 6-->28-->496 Display: 496 28 6 Delete: position 1 28->6 P10: Write a C program that uses functions to perform the following: a) Create a singly linked list of squares of integers between 1 to 50. b) Delete the previous node from a given position(read position)from the above linked list. c) Display the above given list in descending order. Test Case 1: 16-->9-->4-->254964 Result: The number not in range 1-50 Test Case 2: 16-->9-->4-->254964 Display: 49 25 16 9 4 Delete: pos 1 Previous element not exist Pos=2 942549

17 | P a g e

APPLICATIONS: Various applications of Singly Linked List are: A singly-linked list is ideally suited to stacks (last in, first out). The list maintains a link with the head node in the list and each node points to the next node in the list (the last node points to NULL). When a new node is added it is added to the head of the list. Since enqueue and dequeue both occur at the head of the list, processing is always in constant time [O(1)]. VIVA VOICE QUESTIONS 1. The linked list structure is defined as a. struct node b. node { { int item; int item; struct node *next; struct node *next; }; };

c. struct node { int item; struct node *next; };

d. node { int item; node next; };

2.Single linked list uses _ _ _ _ _ _ no. of pointers a. Zero b. one c. Two d. Three 3. No.of pointers to be manipulated in a linked list to insert an item in the middle _ _ _ __ _ _ _ a. Two b. Three c. One d. Zero 4. Linked lists are not suitable for data structures of which one of the following problem? a. insertion sort b. Binary search c. radix sort d. polynomial manipulation problem 5. The linked list field(s) are a. data b. pointer c. pointer to next node

18 | P a g e

d. data and pointer to next node

Experiment No: 2 Experiment as given in the JNTUH curriculum. Week2: Write a C program that uses functions to perform the following: a) Create a doubly linked list of integers. b) Delete a given integer from the above doubly linked list. c) Display the contents of the above list after deletion. AIM: To implement doubled linked list of integers in data structure using functions. THEORY: A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.

Following is representation of a DLL node in C language. /* Node of a doubly linked list */ struct node { int data; struct node *next; // Pointer to next node in DLL struct node *prev; // Pointer to previous node in DLL }; Following are advantages/disadvantages of doubly linked list over singly linked list. Advantages over singly linked list 1) A DLL can be traversed in both forward and backward direction. 2) The delete operation in DLL is more efficient if pointer to the node to be deleted is given. In singly linked list, to delete a node, pointer to the previous node is needed. To get this previous node, sometimes the list is traversed. In DLL, we can get the previous node using previous pointer. Disadvantages over singly linked list 1) Every node of DLL Require extra space for an previous pointer. It is possible to implement DLL with single pointer though. 2) All operations require an extra pointer previous to be maintained. For example, in insertion, we need to modify previous pointers together with next pointers. For example in following functions for insertions at different positions, we need 1 or 2 extra steps to set previous pointer.

19 | P a g e

Insertion A node can be added in four ways 1) At the front of the DLL 2) After a given node. 3) At the end of the DLL 4) Before a given node.

1.Insertion at the front of list

2.Insertion in the middle of the list

20 | P a g e

3.Insertion at the end of the list

Deletion Write a function to delete a given node in a doubly linked list. (a) Original Doubly Linked List

(a) After deletion of head node

(a) After deletion of middle node

(a) After deletion of last node

21 | P a g e

ALGORITHM : Initialize the first and last nodes with NULL values struct node *first=NULL,*last=NULL,*next,*prev,*cur; 1. Algorithm creating a new node: Step 1: if the list is empty then first==NULL Step 2: Create a new node cur=(struct node*) malloc (sizeof (struct node)); Step 3: Read the content of node Step 4: Assign new node left and right links to NULL cur->left=NULL; cur->right=NULL;

Step 5: Assign new node to first & last node first=cur last=cur Step 6: If the list is not empty call insert function insert () Step 7 : Stop 2. Algorithm for Inserting a new node: Step 1 : Initialize count c to 1 Step 2 : Create inserting node cur=(struct node*)malloc(sizeof (struct node)); Step 3: Read the content of node Step 4: Read the position of insertion Step 5: Inserting in first position Check if the pos=1 and first!=NULL cur->right=first; cur->left=NULL; first=cur;

Step 6: Inserting in a given position next=first; repeat the steps a to c until c < pos a. prev=next; b. next=prev->right; c. c++; prev->right=cur; cur->right=next;

Step 7 : Stop

22 | P a g e

3. Algorithm for Deleting a node: Step 1 : Initialize count c to 1 Step 2 : Read the position for deletion Step 3 : Check if first=NULL print list is empty Step 4 : If the list contains single element Check if pos=1 and first->right=NULL print deleted element is first->data Step 5 : Assign first to NULL first=NULL; Step 6 : If the list contains more than one element and to delete first element if pos=1 and first->right!=NULL cur=first; first=first->right; cur->right=NULL;

print deleted element is cur->data free(cur);

Step 7 : If the list contains more than one element and to delete an element at given position next=first; repeat the steps a to c until c < pos a. cur=next; b.next=next->right; c. c++; cur->right=next->right; next->right=NULL; next->left=NULL;

print deleted element is next->data free(next);

Step 8 : Stop 4. Algorithm for Displaying a node: Step1 : Check if first node is NULL print list is empty Step2: If first node is not NULL then cur=first; repeat the steps a to b until cur!=NULL a . print cur->data b . cur=cur->right; Step3 : Stop

23 | P a g e

INPUT & OUTPUT: Insert() : 10 20 30 40 50 Display () : 10->20->30->40->50 Delete() : 40 Display() : 10->20->30->50

PROBLEM DEFINITIONS DIFFERENT FROM JNTU TOPICS FOR WEEK-2 P1: Write a C program that uses functions to perform the following: a) Create a doubly linked list of even integers between 1 to 100. b) Delete the nodes which are divisible by 5 from the above linked list. c) Display the first five contents of the above list after deletion. Test Case 1: 12 10 15 Result : 12->10 Number not in range or not even Test Case 2: 10 12 24 34 40 44 66 68 Result: display: 10 12 24 34 40 44 66 68 delete: 10 40 display:12 24 34 44 66 68 P2: Write a C program that uses functions to perform the following: a) Create a doubly linked list of odd integers between 1 to 50. b) Delete the nodes which are multiples of 3 from the above linked list. c) Display the last five contents of the above list after deletion. Test Case 1: 9 11 51 Result : 9->11 Number not in range or not odd Test Case 2: 9-->11-->13-->17-->19-->23-->25--> Result: display: 9-->11-->13-->17-->19-->23-->25--> deleted: 9 display: 25-> 23-> 19-> 17->13 P3: Write a C program that uses functions to perform the following: a) Create a doubly linked list of prime integers between 10 to 100. b) Delete the nodes which are less than 30 from the above linked list. c) Display the nodes from the given position(read position). Test Case 1: 11->37>41>43>7 Result: 11->37>41>43> Number not in range or not prime Test Case 2: 11->37>41>43

24 | P a g e

Delete: 37>41>43 Display: position 2 41->43 P4: Write a C program that uses functions to perform the following: a) Create a doubly linked list of integers divisible by 5 between 100 to 1000. b) Delete the nodes which are greater than 500 from the above linked list. c) Display the nodes from the beginning of list to the given position(read position). Test Case 1: 600-->700-->500-->400-->300-->24 Result: 600-->700-->500-->400-->300 the number is not divisible by 5 or not in range Test Case 2: 600-->700-->500-->400-->300 Display :position 3 600-->700-->500 Deleted:600 700 P5: Write a C program that uses functions to perform the following: a) Create a doubly linked list of integers which are multiple of 3 between 1 to 100. b) Delete the nodes which are multiple of 5 from the above linked list. c) Display the nodes between 50 to 100 from the above given list. Test Case 1: 9-->3-->6-->75-->15-->123 Result: the number is not multiple of 3 or not in range Test Case 2: 9-->3-->6-->75-->15-->123 Display:75-> Delete: 75 15 9-->3-->6 P6: Write a C program that uses functions to perform the following: a) Create a doubly linked list of integers less than 100. b) Delete the nodes which are greater than 50 from the above linked list. c) Display the nodes between 75 to 100 from the above given list. Test Case 1: 45-->23-->56-->89-->99--> Result: 45-->23-->56-->89-->99--> 123 the number is not less than 100 Test Case 2: 45-->23-->56-->89-->99--> Display: 89-->99--> Delete: 56 89 99 45-->23 P7: Write a C program that uses functions to perform the following: a) Create a doubly linked list of integers greater than 100. b) Delete the nodes which are less than 500 from the above linked list. c) Display the above given list in ascending order. Test Case 1: 600-->200-->300-->500-->600-->900-->90 Result: the number is not greater than 100 Test Case 2: 600-->200-->300-->500-->600-->900 Display: data in ascending order is 200 300 500 600 600 900

25 | P a g e

Delete: 200 300 600-->500-->600-->900 P8: Write a C program that uses functions to perform the following: a) Create a doubly linked list of integers between 100 to 1000. b) Delete the nodes which are multiple of 10 from the above linked list. c) Display the nodes which are multiples of 3 from the above given list. Test Case 1: 345-->315-->310-->200-->100-->1000-->1001 Result: the number is not in range 100-1000 Test Case 2: 345-->315-->310-->200-->100-->1000 Display: 345-->315 Delete: 310 200 100 1000 345-->315 P9: Write a C program that uses functions to perform the following: a) Create a doubly linked list of perfect integers between 1 to 1000. b) Delete a node from a given position(read position)from the above linked list. c) Display the above given list in reverse order. Test Case 1: 6-->28-->496-->455 Result: the number is not in range 1-1000 or not perfect number Test Case 2: 6-->28-->496 Display: 496 28 6 Delete: position 1 28->6 P10: Write a C program that uses functions to perform the following: a) Create a doubly linked list of squares of integers between 1 to 50. b) Delete the previous node from a given position(read position)from the above linked list. c) Display the above given list in descending order. Test Case 1: 16-->9-->4-->254964 Result: The number not in range 1-50 Test Case 2: 16-->9-->4-->254964 Display: 49 25 16 9 4 Delete: pos 1 Previous element not exist Pos=2 942549

26 | P a g e

APPLICATIONS: 1.Applications that have an MRU list (a linked list of file names) 2. The cache in your browser that allows you to hit the BACK button (a linked list of URLs) 3. Undo functionality in Photoshop or Word (a linked list of state) 4. A stack, hash table, and binary tree can be implemented using a doubly linked list. 5. A great way to represent a deck of cards in a game. VIVA VOICE QUESTIONS 1.In a linked list with n nodes, the time taken to insert an element after an element pointed by some pointer is (A) 0 (1) (B) 0 (log n) (C) 0 (n) (D) 0 (n 1og n) Ans:A 2.A linear collection of data elements where the linear node is given by means of pointer is called (A) linked list (B) node list (C) primitive list (D) None of these Ans:A 3. Representation of data structure in memory is known as: (A) recursive (B) abstract data type (C) storage structure (D) file structure Ans:B

27 | P a g e

Experiment No: 3 Experiment as given in the JNTUH curriculum. Week3: Write a C program that uses stack operations to convert a given infix expression into its postfix Equivalent, Implement the stack using an array. AIM: To implement stack using array to convert a given infix expression into its postfix Equivalent in data structure using functions. THEORY: Infix To Postfix Conversion Algorithm for converting Infix to Postfix:  If the input is an operand, then place it into the output buffer.  If the input is an operator, push it into the stack.  If the operator in stack has equal or higher precedence than input operator, then pop the operator present in stack and add it to output buffer.  If the input is an open brace, push it into the stack  If the input is a close brace, pop elements in stack one by one until we encounter close brace. Discard braces while writing to output buffer. Infix Expression: (a - b) / (c + d) Input: ( Input is open brace. So, place it into the stack. | | | ( | ------

Output:

Input: a Place the operand in output buffer. | | | ( | ------

Output: a

Input: Place the operator into the stack. | | | - | | ( | ------

Output: a

Input: b Place the operand in output buffer | | | - |

28 | P a g e

| ( | -------

Output: ab

Input: ) Pop '-' and '(' | | |

| | | -------

Output: ab-

Input: / Push the operator into the stack. | | | | | / | -------

Output: ab-

Input: ( Push open brace into the stack. | | | ( | | / | -------

Output: ab-

Input: c Place the operand in output buffer. | | | ( | | / | -------

Output: ab-c

Input: + Place the operator into the stack. | + | | ( | | / | -------

Output: ab-c

Input: d Place the operand in output buffer. | + | | ( | | / | -------

29 | P a g e

Output: ab-cd

Input: ) Pop all elements until we get open brace. | | | | | / | ------

Output: ab-cd+

No more input to parse. So, pop all other elements from the stack | | |

| | | ------

Output: ab-cd+/

ALGORITHM: 1. Algorithm for postfix conversion: void postfix(char inf[15]) Step 1: repeat the steps a to c until inf[i]!='\0' a.check if infix expression is opening brace push it onto stack check if(inf[i]='(') push(inf[i]) b. check if infix expression is alphabetic character add it to postfix expression if(isalpha(inf[i])) pf[j++]=inf[i] c. check if infix expression is closing brace if(inf[i]==')') repeat 1 to 2 until stack[top]!=opening brace 1.pf[j++]=pop() 2.x=pop() Otherwise repeat 1 to 2 until prec(stack[top])>=prec(inf[i]) 1.pf[j++]=pop() 2.push(inf[i]) Step 2:repeat the steps a to b until top!=-1 a.pf[j++]=pop() b.pf[j]='\0'

step 3: stop 2. Algorithm for push operation on stack: Step 1:increment top by 1 Step 2: stack[++top]=y Step 3:stop

30 | P a g e

3. Algorithm for pop operation on stack: Step 1:return stack[top] Step 2: decrement top by 1 Step 3:stop

4. Algorithm for finding precedence of operators : Step 1:check if (c=='*' || c=='/' || c=='%') return(5) step 2:check if (c=='+' || c=='-') return(3) Step 3:if(c=='(') return(1) step 4:stop

5. Algorithm for main function : Step 1:start Step 2: read infix expression Step 3:call postfix(infix) Step 4:print postfix expression result Step 5:stop

INPUT: a+b*c OUTPUT: abc*+

PROBLEM DEFINITIONS DIFFERENT FROM JNTU TOPICS FOR WEEK-3 Problem definitions different from JNTU topics for week3 P1: Write a C program that uses stack operations to convert a given infix expression having + and - operators into its postfix Equivalent, Implement the stack using an array. (ex: a+b-c) Test case 1: (a+b-c) Result: ab+cTest case 2: a+(b-c) Result: abc-+ P2: Write a C program that uses stack operations to convert a given infix expression having + and * operators into its postfix Equivalent, Implement the stack using an array. (ex: a+b*c) Test case 1: (a+b*c) Result: abc*+ Test case 2: (a+b)*c 31 | P a g e

Result: ab+c*

P3: Write a C program that uses stack operations to convert a given infix expression having *,% and / operators into its postfix Equivalent, Implement the stack using an array. (ex: a*b%d/c) Test case 1: (a*b%d/c) Result: ab*d%c/ Test case 2: (a*(b%d)/c) Result: abd%*c/ P4: Write a C program that uses stack operations to convert a given infix expression having / and % operators into its postfix Equivalent, Implement the stack using an array. (ex: a/b%c) Test case 1: (a/b%c) Result: ab/c% Test case 2: a/(b%c) Result: abc%/ P5: Write a C program that uses stack operations to convert a given infix expression having && and + operators into its postfix Equivalent, Implement the stack using an array. (ex: a+b && c) Test case 1: (a+b & c) Result: abc&+ Test case 2: (a+b)&c Result: ab+c&

P6: Write a C program that uses stack operations to convert a given infix expression having ^ and * operators into its postfix Equivalent, Implement the stack using an array. (ex: a^b*c ) Test case 1: (a^b * c) Result: abc*^ Test case 2: (a^b)*c Result: ab^c* P7: Write a C program that uses stack operations to convert a given infix expression having < and + operators into its postfix Equivalent, Implement the stack using an array. (ex: a < b + c) Test case 1: (aleft/T->right is NULL and place the new node at T->left(key in new node < key in T)/T->right (key in new node > key in T). If the element to be inserted is greater than the element present in root node, traverse the right sub-tree recursively until we reach T->left/T->right is NULL and place the new node at T->left/T->right.

Binary search tree deletion There are three different cases that needs to be considered for deleting a node from binary search tree. case 1: Node with no children (or) leaf node case 2: Node with one child case 3: Node with two children. Binary search tree searching Binary search tree is a tree in which the key value of left child is less than the parent node and the key value in right child is greater than the root.  

Check whether the root node is NULL or not. If it's NULL, there is no tree available. So, return NULL. If node T has the search element, then return that node.

43 | P a g e

 

If the search element is less than the key in node T, recursively search the left sub tree of T. If the search element is greater than the key in node T, recursively search the right sub tree of T.

THEORY: Tree Traversals Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. Following are the generally used ways for traversing trees. Tree Traversals: (a) Inorder (b) Preorder (c) Postorder Inorder Traversal: Algorithm Inorder(tree) 1. Traverse the left subtree, i.e., call Inorder(left-subtree) 2. Visit the root. 3. Traverse the right subtree, i.e., call Inorder(right-subtree) Uses of Inorder In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder itraversal s reversed, can be used. Preorder Traversal: Algorithm Preorder(tree) 1. Visit the root. 2. Traverse the left subtree, i.e., call Preorder(left-subtree) 3. Traverse the right subtree, i.e., call Preorder(right-subtree) Uses of Preorder Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expression on of an expression tree.

Postorder Traversal: Algorithm Postorder(tree) 1. Traverse the left subtree, i.e., call Postorder(left-subtree) 2. Traverse the right subtree, i.e., call Postorder(right-subtree) 3. Visit the root. 44 | P a g e

Uses of Postorder Postorder traversal is used to delete the tree. Postorder traversal is also useful to get the postfix expression of an expression tree. ALGORITHM: Step 1.declare a structure struct BST { char data; struct BST *left,*right; }node; Step 2: initialize binay search tree root to NULL struct BST* root=NULL,*temp,*cur; 1. Algorithm for creating a binary search tree: Step 1: Start Step2 :Declare c[10] Step3: Initialize temp=root; Step4 : Read the character cur=(struct BST*)malloc(sizeof(struct BST)); Step5: initialize cur->data=c[0] cur->left=NULL cur->right=NULL Step6: Check the node is null assign root to curr if(temp==NULL) root=cur; Step7: repeat until temp!=NULL upto Step 16 Step8 : Check the current data less than temp data if((cur->data))data)) Step9: check the temp->left equal to NULL if(temp->left==NULL) Step 10: Assign temp->left=cur; Step 11 : return Step12 : Assign temp=temp->left; Step13: otherwise check temp right equal to null

45 | P a g e

temp->right==NULL Step14:Assign temp->right=cur; return; Step 15 : otherwise temp=temp->right; Step 16: stop Algortihm postorder(struct BST *temp) Step1: Start Step2: check the temp notequal to null temp!=NULL Step3: call to postorder with temp->left postorder(temp->left); Step4: call to postorder with temp->right postorder(temp->right); Step5: print temp->data Step6: stop

INPUT & OUTPUT: ABC CBA Problem definitions different from JNTU topics for week5 P1: Write a C program that uses functions to perform the following: a) Create a binary search tree of capital alphabets. b) Traverse the above Binary search tree recursively in Preorder. Test case 1: A B C a Result: A B C lower case letters are not allowed Test case 2: D C E B F Result: D C E B F P2: Write a C program that uses functions to perform the following: a) Create a binary search tree of small case alphabets. b) Traverse the above Binary search tree recursively in inorder. Test case 1: a b c A Result: a b c upper case letters are not allowed

46 | P a g e

Test case 2: d c e b f Result: b c d

e

f

P3: Write a C program that uses functions to perform the following: a) Create a binary search tree of lower case vowels. b) Traverse the above Binary search tree recursively in Postorder. Test case 1: i o e u a x Result: i o e u a consonant letters are not allowed Test case 2: i o e u a Result: a e u o i P4: Write a C program that uses functions to perform the following: a) Create a binary search tree of consonants. b) Traverse the above Binary search tree recursively in converse Postorder. Test case 1: a Result: vowels are not allowed dcfbg Test case 2: d c f b g Result: g f b c d P5: Write a C program that uses functions to perform the following: a) Create a binary search tree of upper case vowels symbols. b) Traverse the above Binary search tree recursively in converse Preorder. Test case 1: a Result: small case vowels are not allowed IEOAU Test case 2: I E O A U Result: I O U E A

P6: Write a C program that uses functions to perform the following: a) Create a binary search tree of capital alphabets and operators(+,*,/). b) Traverse the above Binary search tree recursively in converse Inorder. Test case 1: A + B - * a Result: small case letters are not allowed A+B-* Test case 2: A + B - * Result: B A + * P7: Write a C program that uses functions to perform the following: a) Create a binary search tree of small alphabets and operators(%,-,*). b) Traverse the above Binary search tree recursively in preorder. Test case 1: a % - b * A

47 | P a g e

Result: Upper case letters are not allowed a % * b Test case 2: a % - b * Result: a % * b

P8: Write a C program that uses functions to perform the following: a) Create a binary search tree for a given infix expression.(a+b*c) b) Traverse a specific node of the above Binary search tree recursively in Inorder. Test case 1: a + b * c A Result: Upper case letters are not allowed Test case 2: a + b * c Result: * + a b

c

P9: Write a C program that uses functions to perform the following: a) Create a binary search tree for a given prefix expression.(-a/bc) b) Traverse a specific node of the above Binary search tree recursively in preorder. Test case 1: - a / b c B Result: Upper case letters are not allowed Test case 2: - a Result: a

/ b c / b

c

P10: Write a C program that uses functions to perform the following: a) Create a binary search tree for a given postfix expression.(a*b% c) b) Traverse a specific node of the above Binary search tree recursively in postorder. Test case 1: a * b % c C Result: Upper case letters are not allowed Test case 2: a * b % c Result: % * c b

a

APPLICATIONS: 1. 2. 3. 4. 5.

Used in many search applications where data is constantly entering/leaving, such as the map and set objects in many languages' libraries. Binary Space Partition - Used in almost every 3D video game to determine what objects need to be rendered. Binary Tries - Used in almost every high-bandwidth router for storing router-tables. Hash Trees - used in p2p programs and specialized image-signatures in which a hash needs to be verified, but the whole file is not available. Heaps - Used in implementing efficient priority-queues, which in turn are used for scheduling processes in many operating systems, Quality-of-Service in routers, and

48 | P a g e

A* (path-finding algorithm used in AI applications, including robotics and video games). Also used in heap-sort. 6. Huffman Coding Tree - used in compression algorithms, such as those used by the .jpeg and .mp3 file-formats. .

VIVA VOICE QUESTIONS: 1.Every binary tree with n elements have _ no of edges a)n

b)n-1

c)n-2

d)n+1

2.Define inorder traversal a)left,root,right

b)root,left,right

c)left,right,root

d)none

c)left,right,root

d)none

c)right,left,root

d)none

3. Define postorder traversal a)left,root,right

b)root,left,right

4. Define converse postorder traversal a)left,root,right

49 | P a g e

b)root,left,right

Experiment No: 7 (A) AIM: Write C programs for implementing the following sorting methods to arrange a list of integers in Ascending order using Insertion sort THEORY: Example: The following table shows the steps for sorting the sequence {3, 7, 4, 9, 5, 2, 6, 1}. In each step, the key under consideration is underlined. The key that was moved (or left in place because it was biggest yet considered) in the previous step is shown in bold. 37495261 37495261 37495261 34795261 34795261 34579261 23457961 23456791 12345679

ALGORITHM 1. Algorithm: Insertion_Sort (int A[20],int n) Step 1: Start Step 2: Declare integer variables i, j, index Step 3: for i from 1 to i0) && (a[j-1]>index)) { a[j]=a[j-1] j=j-1 } d) a[j]=index

50 | P a g e

Step 4: print a[i] Step5: stop 2. Algorithm Main Function: main () Step 1: Declare an integer variables n, i, a [20] Step 2: Read size of array n Step 3: Read the elements of an array a[i] Step 4: call the sub function Insertion_Sort (a,n) INPUT: {3, 7, 4, 9, 5, 2, 6, 1}. OUTPUT: 1 2 3 4 5 6 7 9 PROBLEM DEFINITIONS DIFFERENT FROM JNTU TOPICS FOR WEEK7 P1: Write C program for implementing the insertion sort method to arrange a list of even integers between 1 to 100 integers in ascending order. Test Case 1: 56 90 20 10 15 Not Even 10 20 56 90 P2: Write C programs for implementing the insertion sort method methods to arrange a list of odd integers between 1 to 100 integers in ascending order. Test Case 1: 55 91 21 11 16 Not Odd 11 21 55 91 P3: Write C programs for implementing the insertion sort method to arrange a list of integer divisible by 3 & 5 between 10 to 100 integers in ascending order Test Case 1: 15 90 25 45 10 Not divisible 3 or 5 15 25 45 90 P4: Write C programs for implementing the insertion sort method to arrange a list of integer divisible by 5 between 100 to 1000 in ascending order. Test Case 1: 150 910 220 715 14 Not divisible by 5 150 220 715 910 P5: Write C programs for implementing the insertion sort method to arrange a list of integer multiple of 3 between 1 to 100 in Ascending order Test Case 1: 56 90 15 10 Not Multiple of 3 15 56 90 P6: Write C programs for implementing the insertion sort method to arrange a list of integer less than 100 & divisible by 3 & 6 in ascending order. Test Case 1: 56 90 20 10 150 51 | P a g e

Greater than 100 10 20 56 90 P7: Write C programs for implementing the f insertion sort method to arrange a list of integer greater than 100 & multiply of 4 in ascending order Test Case 1: 156 190 120 100 90 Less than 100 100 120 156 190 P8: Write C programs for implementing the insertion sort method to arrange a list of integer between 100 to 1000 in ascending order. Test Case 1: 156 190 200 500 1500 Not in range 100 1000 156 190 200 500 P9: Write C programs for implementing the insertion sort method to arrange a list of cube integer between 1 t0 500 in ascending order. Test Case 1: 5 4 3 2 10 Not in range 1 - 500 8 27 64 125 P10: Write C programs for implementing the insertion sort method to arrange a list of squares of integers between 1 to 50 in ascending order. Test Case 1: 5 4 3 2 10 Not in range 1 - 50 4 9 16 25 APPLICATIONS: VIVA VOICE QUESTIONS: 1. Define insertion sort? 2. What is the average & worst Time complexity of an insertion sort? 3. Difference between bubble sort & insertion sort?

52 | P a g e

EXPERIMENT NO: 7 (B) Write C programs for implementing the Merge sort methods to arrange a list of integers in ascending order AIM: To implements the Merge sort methods to arrange a list of integers in ascending order THEORY: Merge sort is based on Divide and conquer method. It takes the list to be sorted and divide it in half to create two unsorted lists. The two unsorted lists are then sorted and merged to get a sorted list. The two unsorted lists are sorted by continually calling the merge-sort algorithm; we eventually get a list of size 1 which is already sorted. The two lists of size 1 are then merged.

Properties:

Best case – When the array is already sorted O(nlogn). Worst case – When the array is sorted in reverse order O(nlogn). Average case – O(nlogn). Extra space is required, so space complexity is O(n) for arrays and O(logn) for linked lists.

ALGORITHM: Globally declaring array int a[100] 1. Algorithm: Merge_Sort(int a[100],int low,int high) Step1: Start Step2: Declare an integer middle variable int mid Step3: Check the condition low less than high if(lown Step20 return Success; Step21:check if (pos == M – 1) upto step23 otherwise gotostep 24 Step22: lastKey = newKey; Step23: lastPtr = newPtr; Step24: else lastKey = ptr->keys[M-2]; Step25: lastPtr = ptr->p[M-1]; Step26 : repeat for (i=M-2; i>pos; i--) { ptr->keys[i] = ptr->keys[i-1]; ptr->p[i+1] = ptr->p[i]; } Step27: ptr->keys[pos] = newKey; Step28: ptr->p[pos+1] = newPtr; } Step29: splitPos = (M - 1)/2; Step30: (*upKey) = ptr->keys[splitPos]; Step31:(*newnode)=malloc(sizeof(struct node)); Step32: ptr->n = splitPos; Step33:(*newnode)->n = M-1-splitPos; Step34: repeat upto step 37 for (i=0; i < (*newnode)->n; i++) Step35: (*newnode)->p[i] = ptr->p[i + splitPos + 1]; Step36: check if(i < (*newnode)->n - 1) (*newnode)->keys[i] = ptr->keys[i + splitPos + 1]; Step37: else (*newnode)->keys[i] = lastKey; Step38: (*newnode)->p[(*newnode)->n] = lastPtr; Step39: return InsertIt; Step40: Stop 3. Algorithm :void insert(int key) Step1: Start Step2: Declare struct node *newnode; int upKey; enum KeyStatus value; Step3:value=ins(root,key,&upKey,&newnode); Step4: Check if (value == Duplicate) Step5:print Key already available Step6: check if (value == InsertIt) { struct node *uproot = root; root=malloc(sizeof(struct node)); root->n = 1; root->keys[0] = upKey;

69 | P a g e

root->p[0] = uproot; root->p[1] = newnode; } Step7: Stop 4:Algorithm: void display(struct node *ptr, int blanks) Step1:Start Step2: Check if (ptr) upto step9 Step3:Repeat for(i=1;in; i++) Step6: print ptr->keys[i] Step7: print "\n" Step8: repeat for (i=0; i n; i++) Step9: call sub function display(ptr->p[i], blanks+10) Step10: Stop

5.Algorithm :int main() Step1: Start Step2: Declare int key,ch Step3:Read the Creation of B tree for node M Step4: repeat while(1) upto step 7 Step5:Read 1.Insert\n2.Display\n3.Quit Step6:Read the your choice ch Step7: switch(ch) case 1: printf("Enter the key : "); scanf("%d",&key); insert(key); break; case 2: printf("Btree is :\n"); display(root,0); break; case 3: exit(0); default:printf("Wrong choice\n"); break; Step8: stop

70 | P a g e

Week 9(b): Write a C program for implementing Heap sort algorithm for sorting a given list of integers in ascending order. Globally declaring int a[10], n, i, j, c, root, temp; 1. Algorithm :void maxheap() Step1: Start Step2: repeat from step 2 to step 11 for (i = 1; i < n; i++) Step3: c=i Step4: repeat from step 5 to step to step 11 do Step5: root = (c - 1) / 2; Step6: check root less than c upto step 9 if (a[root] < a[c]) /* to create MAX heap array */ Step7: temp = a[root] Step8: a[root] = a[c] Step9: a[c] = temp; Step10: c = root; Step11: while (c != 0); Step12 print Max Heap array a[i] Step13: stop 2. Algorithm: main() Step1: start Step2: Read n no of elements Step3: Read the array of elements a[i] Step4: Call sub program maxheap() Step5: Repeat from step 6 to step 19 for (j = n - 1; j >= 0; j--) Step6: temp = a[0]; Step7: a[0] = a[j]; /* swap max element with rightmost leaf element*/ Step8: a[j] = temp; Step9: root = 0; Step10: Repeat from step 11 to step 19 do Step11: c = 2 * root + 1; /* left node of root element */ Step12: Check if ((a[c] < a[c + 1]) && c < j-1) Step13: c++; Step14: Check if (a[root]