Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #10

Similar documents
CS11001 Programming and Data Structures, Autumn 2010

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #12

CS13002 Programming and Data Structures, Spring 2005

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #09. Topic: Structures in C Date:

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Data and File Structures Laboratory

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Binary Trees. Height 1

Linked List. April 2, 2007 Programming and Data Structure 1

Computer Science Foundation Exam

The time and space are the two measure for efficiency of an algorithm.

INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #07. Topic: Pointer in C Date:

only in the space provided. Use any other space for rough work. The question paper has total 12 pages. Rough Work

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes

Procedural programming with C

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Introduction to C Language (M3-R )

Delhi Noida Bhopal Hyderabad Jaipur Lucknow Indore Pune Bhubaneswar Kolkata Patna Web: Ph:

CS201 Some Important Definitions

Binary Trees and Binary Search Trees

CSCE 2014 Final Exam Spring Version A

DC54 DATA STRUCTURES DEC 2014

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

ECE264 Spring 2013 Final Exam, April 30, 2013

Draw a diagram of an empty circular queue and describe it to the reader.

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

Programming. Lists, Stacks, Queues

Linked Lists. .. and other linked structures. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

ALGORITHM 2-1 Solution for Exercise 4

Binary Trees. Examples:

Computer Science E-119 Practice Midterm

Computer Science Foundation Exam. Dec. 19, 2003 COMPUTER SCIENCE I. Section I A. No Calculators! KEY

LINKED LIST IMPLEMENTATION USING C LANGUAGE: A REVIEW

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Data Structure. Chapter 5 Trees (Part II) Angela Chih-Wei Tang. National Central University Jhongli, Taiwan

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #06

Data Structure and Algorithm Homework #3 Due: 2:20pm, Tuesday, April 9, 2013 TA === Homework submission instructions ===

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

CSCE 110 PROGRAMMING FUNDAMENTALS

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

M1-R4: Programing and Problem Solving using C (JAN 2019)

I2206 Data Structures TS 6: Binary Trees - Binary Search Trees

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

Computer Science Foundation Exam

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #13

Practice Sheet #07 with Solutions

Computer Science /21/2000

MLR Institute of Technology

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

8. Binary Search Tree

CSL 201 Data Structures Mid-Semester Exam minutes

Subject: Fundamental of Computer Programming 2068

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

Ashish Gupta, Data JUET, Guna

ECE 2400 Computer Systems Programming, Fall 2017 Prelim 1 Prep

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

Computer Science Foundation Exam

DATA STRUCTURES AND ALGORITHMS

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

CSCI 171 Chapter Outlines

CS32 - Week 2. Umut Oztok. July 1, Umut Oztok CS32 - Week 2

CSE 333 Midterm Exam 2/14/14

Computer Science Foundation Exam

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Solution to CSE 250 Final Exam

CSE 2320 Section 002, Fall 2015 Exam 2 Time: 80 mins

ECE 2400 Computer Systems Programming Fall 2018 Topic 7: Concrete Data Types

Introduction to Computer Science Midterm 3 Fall, Points

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging.

S.E. Sem. III [INFT] Data Structures & Analysis. Primitive Linear Non Linear

Outline. Preliminaries. Binary Trees Binary Search Trees. What is Tree? Implementation of Trees using C++ Tree traversals and applications

Chapter 17: Linked Lists

Section I B COMPUTER SCIENCE SOLUTION

Multi-way Search Trees! M-Way Search! M-Way Search Trees Representation!

Advanced Programming. Lists. A list is a data structure based on usage of pointers and dynamic allocation of memory.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS

struct node{ int info; struct node *left, *right; }; typedef struct node nodeptr; A Linear Doubly Linked List

Linked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra

BBM 201 DATA STRUCTURES

Elementary Data Structures: Lists

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

Exam Principles of Imperative Computation, Summer 2011 William Lovas. June 24, 2011

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

Lecture Notes on Memory Layout

ECE264 Fall 2013 Exam 3, November 20, 2013

NET/JRF-COMPUTER SCIENCE & APPLICATIONS. Time: 01 : 00 Hour Date : M.M. : 50

S.E. Sem. III [CMPN] Data Structures. Primitive Linear Non Linear

CHAPTER 4 FUNCTIONS. 4.1 Introduction

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Linked Lists. Gaddis Ch. 17. CS 2308 :: Spring 2016 Molly O'Neil

Transcription:

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur Practice Sheet #10 Topic: Linked Lists Date: 01-03-2017 1. You are given a linked list. Your task is to create two new linked lists, the first of which should contain the 1st, 3rd, 5th,..elements and the second the 2nd, 4th, 6th,.. elements of the input list. The following code segment provides a solution. Fill in the blanks to complete the segment. Evaluation of your answer will depend on overall correctness. The function createlists assumes that there is a dummy node at the beginning of each list (input as well as output). The input list is headed by the pointer head. Oddnumbered elements are to be stored in the list headed by the pointer oddhead, and the even-numbered elements are to be stored in the list headed by the pointer evenhead. Assume that the input pointer head already points to a properly allocated list with a dummy node at the beginning. Assume also that both oddhead and evenhead are already allocated memory only for the dummy nodes. We number the elements of the input list from 1. /* First define a structure for a node in the list */ typedef struct nodetag int data; /* Declare the self-referencing pointer */ next; node; void createlists ( node *head, node *oddhead, node *evenhead ) node *src, *dest1, *dest2; int flag = 1; /* Initialize the source and destination pointers to point to the dummy nodes */ src = head; dest1 = oddhead; dest2 = evenhead; /* As long as the source list is not fully traversed */ while ( ) if (flag == 1) /* Insert in the odd list */ /* Allocate memory for a new node */ /* Advance the destination pointer by one node */ /* Copy data from source */ else /* Insert in the even list */ /* Allocate memory for a new node */ /* Advance the destination pointer by one node */ /* Copy data from source */ src = src -> next; /* Look at the next node in the input */

if (flag == 1) flag = 2; else flag = 1; /* Switch the destination */ dest1 -> next = dest2 -> next = NULL; /* Terminate the destination lists */ 2. We are given a linked list and we want to traverse it in a way such that the links are reversed by the time we complete the traversal. Complete the function traversereverse that achieves this objective. You can assume that the input pointer is not NULL. Do not use any new variables or malloc/calloc instructions. your program should accomplish the goal by careful manipulation of the pointers. (a) (! (x>=z)) (b) (x<=z) (c) ((x<y) && (y<z)) (d) ((x<y) (y<z)) struct node char data; struct node *link; ; struct node *traversereverse ( struct node *p1 ) struct node *p2, *p3; /* p2 points the part of the list that has already been reversed and p1 points to the part that is yet to be reversed. p3 may be used as an auxiliary pointer. */ /* Initialize the pointers */ p2 = p1; p1 = p1->link; p2->link = NULL; /* As long as the unprocessed part contains more nodes to process */ while ( ) /* Reverse another link from the unprocessed part. Use pointer assignments only. */ p1->link = p2; /* Link p1 to head the reversed list */ return ; /* Return a pointer to the header of the reversed list */ 3. The following function recreverse recursively reverses a linked list. Which one of the two functions would you prefer and why? struct node *recreverse ( struct node *p ) struct node *q, *head; if (p->link == NULL) return p; /* one node */ /* Recursively reverse the list of at least 2 nodes minus first element */ head = p; p = p->link; q = p = recreverse(p); /* Append the first node at the end of the reversed list */ while (q->link!= NULL) q = q->link; q->link = head; head->link = NULL; return p; Page 1

4. (a) Give a suitable typedef to represent a linked list of integers. (b) Write the C function which takes a list of integers, an integer i and another integer d. It enters d after the i-th element in the list. If i = 0, then it enters at the beginning of the list. Mention clearly whether a dummy header node is used in your function. (c) In a circular linked list, the next pointer of the last node points to the starting node of the list. Write a recursive C function that prints the elements of a circular linked list of integers in the reverse order (that is, from end to beginning). Use the following function prototype: void printclist ( clist l, const clist h ); Here the second parameter points to the beginning of the list and is kept constant across the calls. Assume that no dummy header node is used in the circular linked list. 5. Consider the type definitions given below. Suppose that a linked list is made up of nodes of type struct node. The last node points to NULL. struct node int key; struct node * next; ; typedef struct node* link; 6. (a) Write a function deletesecond() to delete the second node of the list, given head which points to the first element of the list. Assume that there are at least two nodes on the list. (b) Write a function count() that takes the head of a linked list as input, and returns the number of nodes in the linked list. (c) Consider the following function baz() that takes a pointer to the first node of a linked list. void baz (link head) if (head == NULL) return ; baz (head->next->next) ; printf ( %d, head->key) ; What will be printed when the function is called with the linked list shown below? Head -> 1 - > 2 -> 3 -> 4 -> 5 -> 6 - (d) Consider the same linked list as shown in the previous figure, with head pointing to the first node of the list. Show the changes in the list structure after the following code segment is executed by drawing a diagram. Clearly indicate where, q and p point to after the execution of the program segment. link head, q, p; q = NULL; while(head!=null) Page 2

Page 3 p=head; head = head->next; p->next = q; q = p; 7. Assume that you are given a linked list with an even number of nodes (excluding the dummy node at the beginning). Your task is to write a function in order to locate the middle of the list, and to subsequently insert two new elements in that middle position. For the sake of ease of programming, you may assume that a dummy node is maintained at the beginning of a linked list. Assume you have a linked list with six elements 43, 71, 82, 9, 37, 64. After inserting two new elements 91 and 5 at the middle, the list changes to 43, 71, 82, 91, 5, 9, 37, 64. In order to locate the middle of the list, we use two pointers p and q. They are initialized to point to the first node of the list (the dummy node). Subsequently, in a loop, p advances down the list by two cells, whereas q advances down the list by one cell. When p reaches the end of the list, the pointer q is ready for insertion at the middle. Do not allocate two cells together in a single memory allocation call, since if you do so, you cannot free a cell individually. typedef struct _node int data; node; void insertmid (node *head, int n1, int n2 ) node *p, *q; /* Do not use any other variable */ p = q = head; /* While the middle of the linked list is not located */ while (!= NULL ) p = ; /* p advances by two cells */ q = ; /* q advances by one cell */ /* Here, q points to the node after which insertion will be made */ /* Allocate memory to the first new node */ p = ; /* Allocate memory to the second new node */ /* Set the data fields */ p -> data = ; = n2; /* Establish link from the second node created */ /* Establish link from the list to include the new nodes */ 8. What is the output of the following program? struct node int cval; struct node *next; main() struct node N1, N2, N3; N1.cval = 1; N2.cval = 10; N3.cval = 100;

Page 4 N1.next = &N2; N2.next = &N3; N3.next = &N1; printf("%d,%d", N2.next -> cval, N2.next -> next -> cval); (a) 1,10 (b) 1,100 (c) 10,100 (d) 100,1 9. In this exercise, we deal with linked lists. In the linked list (say L1), if a node stores the integer n, the next node stores the integer n n. This means that we have a list of monotonically decreasing integers. The list terminates after the node containing the value 0. Define a node in the list in the usual way: typedef struct _node int data; struct _node *next; node; (a)write a function to create a single list as explained above. The list starts with a supplied integer value n, and subsequently uses the above formula for the subsequent nodes. node *genseq1 ( int n ) node *L, *p; /* Create the fist node to store n */ L = /* Initialize the running pointer p for subsequent insertions */ p = ; while ( ) /* As long as n is not reduced to zero */ /* Compute the next value of n */ n -= ; /* Allocate memory */ /* Store n in the new node, and advance */ /* Terminate the list */ return L; /* Return the header */ (b) Now, we create another list (say L2). This second list starts with another value, and contains nodes storing integer values satisfying the same formula used in the first list. After some iterations, two lists must encounter a common value. From this node onwards, the second list follows the same nodes and links as the first list. Complete the following C function to create the second list. The header to the first list is passed to this function. Also, the starting value n for the second list is passed. node *genseq2 ( node *L1, int n ) node *L2, *p1, *p2;

Page 5 /* Skip values in the first list larger than n */ p1 = L1; while ( ) p1 = p1 -> next; /* If n is already present in the first list */ if ( ) return ; /* Create the fist node in the second list to store n */ L2 = ; ; /* Initialize the running pointer p for subsequent insertions */ p2 = ; while (1) /* Let us decide to return inside the loop */ n -= -; /* Next value of n */ /* p1 skips all values in the first list, larger than the current n */ while p1 = p1 -> next; if ( ) /* n found in first list */ ; /* Adjust the second list */ Return ; /* Return header to second list */ /* n not found in first list, so create a new node in second list */ (c) Complete the following function that, given the headers L1 and L2 as input, returns a pointer to the first common node in these two lists. node *getintersection ( node *L1, node *L2 ) node *p1, *p2; p1 = ; p2 = ; /* Initialize pointers */ while (1) /* Return inside the loop */ /* If the common node is located, return an appropriate pointer */ if ( ) return ; /* else if p1 points to a larger integer than p2 */ else if ( ) ; else ; 10. You are given a linked list of integers which are in ascending order. However, there may be duplicates, which should be removed. Write a C code fragment that removes the duplicates and returns the number of distinct elements in the list. Ans. typedef struct llnodetag //...via struct for linked list of ints int val; // value stored in node struct llnodetag *nextp; // pointer to next node llnodetyp, *llnodeptr ; // type names for struct and pointer to struct 3 int removeduplicates (llnodeptr headp) int elemcount=0; // needs to be incremented when a new value is seen llnodeptr n1p, n2p; n1p = headp; if (n1p!= NULL) // list is not empty // n2p is initialised to point to the successor of n1p n2p = n1p->nextp ; 1

Page 6 elemcount++ ; 1 else return 0; 1 // keep looping to find duplicates while ( n2p! = NULL ) 1 // test for a duplicate if (n1p->val == n2p->val ) // duplicate found 1 // steps to remove the duplicate at n2p n1p->nextp = n2p->nextp ; 1 free(n2p) ; 1 n2p = n1p->nextp ; 1 else // advance in the list n1p = n2p ; 1 n2p n1p->nextp ; 1 elemcount++ ; 1 return elemcount ; // final step 1 11. In this exercise, we deal with linked lists which are kept sorted in the increasing order of the data values. To this end, we define a node in the list in the usual way as: typedef struct _node int data; struct _node *next; node; A list is specified by a pointer to the first node in the list. We assume that all the nodes in the list store valid data items, that is, there is no dummy node at the beginning of the list. Let H be a pointer to the first node in a sorted linked list. H is NULL if the list is empty. We plan to insert a data value a in the list such that the list continues to remain sorted after the insertion. The value a to be inserted may or may not be already present in the list. Complete the following function to carry out this sorted insertion. The function should return a pointer to the first node in the modified list. node *sortedinsert ( node *H, int a ) node *p, *q; /* Create a new node to store the new value */ p = ; /* Allocate memory */ ; /* Store a in the new node */ /* Handle insertion before the first node of the list. This should include the case of insertion in an empty list. */ if ( ) ; return ; /* Now we are in a situation where we insert after a node. We first let q point to the node after which the data item a will be inserted. */ q = ; /* Initialize q for the search */ /* Loop on q to locate the correct insertion position */

Page 7 while ( ) q = q -> next; /* Finally, insert p after q */ ; return ; node *sortedinsert ( node *H, int a ) node *p, *q; /* Create a new node to store the new value */ p = (node *)malloc(sizeof(node)) ; /* Allocate memory */ p -> data = a ; /* Store a in the new node */ /* Handle insertion before the first node of the list. This should include the case of insertion in an empty list. */ if ( (H == NULL) (a <= H -> data) ) p -> next = H; return p ; /* Now we are in a situation where we insert after a node. We first let q point to the node after which the data item a will be inserted. */ q = H ; /* Initialize q for the search */ /* Loop on q to locate the correct insertion position */ while ( (q -> next) && (a > q -> next -> data) ) q = q -> next; /* Finally, insert p after q */ p -> next = q -> next; q -> next = p; return H ; 12. (i) Complete the SortedMerge() function below that takes two non-empty lists, each of which is sorted in increasing order, and merges the them into one list which is in increasing order. SortedMerge() should return the new list. Assume that the elements of the lists are distinct and there are no common elements among the lists. For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20, then SortedMerge() should return a pointer to the head node of the merged list 2->3->5- >10->15->20. The linked list node structure is defined as: struct node int data; struct node *next;. struct node *SortedMerge(struct node *a, struct node*b) struct node *mergedlist, *head; if(a->data < b->data) ; else ; head = mergedlist; while(a!= NULL && b!= NULL) if(a->data < b->data)mergedlist->next = a; ; else mergedlist->next = b; ; mergedlist = mergedlist->next; /* if a list is exhausted before the other */ if(a == NULL) ; else ; return ; struct node *SortedMerge(struct node *a, struct node*b) struct node *mergedlist, *head; if(a->data < b->data) mergedlist = a; else mergedlist = b;

head = mergedlist; while(a!= NULL && b!= NULL) if(a->data < b->data)mergedlist->next = a; a = a->next; else mergedlist->next = b ; b = b->next; mergedlist = mergedlist->next; /* if a list is exhausted before the other */ if(a == NULL) mergedlist->next = b; else mergedlist->next = a; return head; 13. Write C program statements for the following operations. (a) Define a node of a circular linked list which contains a complex number. (b) Assume that the head of the above circular list is pointed by a pointer named head. Write a function which takes the head of the list as argument and returns the sum of complex numbers in the list. Ans.?? 14. Consider the function f defined below. struct item int data; struct item * next; ; int f(struct item *p) return ((p == NULL) (p->next == NULL) ((P->data <= p->next->data) && f(p->next))); For a given linked list p, the function f returns 1 if and only if (a) the list is empty or has exactly one element (b) the elements in the list are sorted in non-decreasing order of data value (c) the elements in the list are sorted in non-increasing order of data value (d) not all elements in the list have the same data value. 15. Consider the following C program segment struct CellNode struct CelINode *leftchild; int element; struct CelINode *rightchild; int Dosomething(struct CelINode *ptr) int value = 0; if (ptr!= NULL) if (ptr->leftchild!= NULL) value = 1 + DoSomething(ptr->leftChild); if (ptr->rightchild!= NULL) value = max(value, 1 + DoSomething(ptr->rightChild)); Page 8

return (value); The value returned by the function DoSomething when a pointer to the root of a nonempty tree is passed as argument is (a) The number of leaf nodes in the tree (b) The number of nodes in the tree (c) The number of internal nodes in the tree (d) The height of the tree 16. Figure out the output of the below code written in C programming language. State relevant assumptions if any during computation. #include<stdio.h> int main() char m= 100; printf("m= %d",m); return 0; (a) Error at Line 5 (b) m=100 (c) Error at Line 4 (d) No output --*-- Page 9