113
Question No. 2 Marks : 18 c) Create an AVL tree for the data items. Show each stage of the tree as it gets built along with the single or double rotations (when needed). (10 points) 3. postorder traversal (5 points) 2. preorder traversal (5 points) 1. inorder traversal (5 points) b) Write the contents of the tree using: a) Create a binary search tree for the data items drawing a diagram to show the final tree after all items have been inserted. (5 points) 23 46 79 21 55 33 44 57 56 The data items listed below are to be used to answer the following parts to this question: [30 pts] Question No. 1 Marks : 30 Total Marks: 135 Total Questions: 7 5. You are allowed to use any development environment like Dev C++ etc. b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem. a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding. 4. Do not ask any questions about the contents of this examination from anyone. 3. Unless stated otherwise, all questions carry a single mark. 2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no grade. 1. The duration of this examination is 90 Mins. Please read the following instructions carefully before attempting any of the questions: Time Allowed: 150 Minutes Final Term Examination - February 2005 CS301 Data Structures www.vujannat.ning.com

CS301 Collection of Old Papers

Embed Size (px)

DESCRIPTION

CS301 Collection of Old Papers

Citation preview

Page 1: CS301 Collection of  Old Papers

Question No. 2 Marks : 18

c) Create an AVL tree for the data items. Show each stage of the tree as it gets built along with the single or double rotations (when needed). (10 points)

3. postorder traversal (5 points) 2. preorder traversal (5 points) 1. inorder traversal (5 points)

b) Write the contents of the tree using:

a) Create a binary search tree for the data items drawing a diagram to show the final tree after all items have been inserted. (5 points)

23 46 79 21 55 33 44 57 56

The data items listed below are to be used to answer the following parts to this question: [30 pts]

Question No. 1 Marks : 30

Total Marks: 135 Total Questions: 7

5. You are allowed to use any development environment like Dev C++ etc.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

4. Do not ask any questions about the contents of this examination from anyone. 3. Unless stated otherwise, all questions carry a single mark.

2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no grade.

1. The duration of this examination is 90 Mins.

Please read the following instructions carefully before attempting any of the questions:

Time Allowed: 150 Minutes

Final Term Examination - February 2005

CS301 Data Structures

www.vujannat.ning.com

Page 2: CS301 Collection of  Old Papers

Let heap stored in an array as A = [3, 8, 4, 9, 11, 5, 6, 10, 12, 13]. Assume that the index of the first array cell is 1 and that this is also the root of the heap (i.e., element 3). In other words, the root of the heap contains the minimum element. What is the result of inserting 7 into this heap? [10 pts]

Question No. 5 Marks : 10

5 none of the above 4 level-order 3 post-order 2 in-order 1 pre-order

Which traversal gives a decreasing order of elements in a heap where the max element is stored at the top? [5 pts]

Question No. 4 Marks : 5

5 342165 4 342615 3 342561 2 325416 1 123456

You can insert as many stack.pop()'s as you like in the above sequence of stack.push's to get a desired output. Which of the following cannot be an output?

stack.push('6'); stack.push('5'); stack.push('4'); stack.push('3'); stack.push('2'); stack.push('1');

Consider the following sequence of push operations in a stack: [5 pts]

Question No. 3 Marks : 5

ABC output(A) output(B) output(C) Show how to produce the other 5 permutations ACB, BAC, BCA, CAB, CBA given the input ABC.

Suppose your input were ABC. Which of the six permutations of ABC can you generate using enqueue(data), dequeue(), and output(data)? Show the operations that yield the permutations that are possible. Explain why any impossible permutations are impossible (it's not enough to show you've tried lots of combinations of operations). To get you started, you can generate:

B A enqueue(A) output(B) output(dequeue()) A B output(A) output(B)

Recall that the abstract data type Queue has operations enqueue(data) (add data to the tail of the queue), and dequeue() (remove data from the head of the queue and return it). With a queue that holds characters, the input sequence AB (ordered from left to right), plus an operation output(character) (print next character from either the input sequence or the queue on standard output) you could generate (processing the input in left-to-right order): [18 pts]

Page 3: CS301 Collection of  Old Papers

} temp = temp->next push temp onto the stack { while (temp is not NULL) temp = thisnode->next

Suppose you are given a pointer "thisnode" that points to some node in a singly linked list (NULL terminated), as well as a stack which can hold pointers to list nodes. If x points to a node in the list, the member "x->next" holds a pointer to the node following x in the list. In 20 words or less, describe what the following pseudo code does: [5 pts]

Question No. 7 Marks : 5

(d) The data structure initially contains n elements. We then insert elements 2, 7, 5, 13, 11, 3 and 1, in that order. We may insert any element, in worst case, in time proportional to log n (i.e., O(log n)) time (3 points)

(c) The data structure initially contains n elements. We then insert elements 7, 14, 27, 68, and 3. We may now find any element, in average case, in constant time (i.e., O(1)) time (3 points)

(b) The data structure is initially empty. We insert the values 2, 4, 6, 8, 10, 1 and 7, in that order. If we want to remove an element, our only choice is 2 (3 points)

(a) The data structure is initially empty. We then insert the values 2, 10, 12, 8, 6 and 4, in that order. Now, the only element we can remove is 12. (3 points)

Stack Queue Binary search tree AVL tree Heap Hash table

For each part of the problem, name and justify one data structure that addresses the problem. Your answer should not be more than 3 lines. You may choose from the following list of data structures: [12 pts]

Question No. 6 Marks : 12

5 [3, 8, 7, 9, 4, 5, 6, 10, 12, 11, 13] 4 [3, 4, 7, 9, 8, 5, 6, 10, 12, 11, 13] 3 [3, 7, 4, 9, 8, 5, 6, 10, 12, 11, 13] 2 [3, 4, 7, 9, 8, 5, 6, 10, 12, 13, 11] 1 [3, 7, 4, 9, 8, 5, 6, 10, 12, 13, 11]

Page 4: CS301 Collection of  Old Papers

temp->next = NULL } temp = temp->next temp->next = pop off stack { while(stack is not empty) temp = thisnode

Page 5: CS301 Collection of  Old Papers

http://vujannat.ning.com BEST SITE TO HELP STUDENTS

FINALTERM EXAMINATION

FALL 2006

CS301 - DATA STRUCTURES (Session - 1 )

Marks: 75

Time: 120min

StudentID/LoginID: ______________________________

Student Name: ______________________________

Center Name/Code: ______________________________

Exam Date: Saturday, February 03, 2007

1. Attempt all questions.

2. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

c. Write all steps, missing steps may lead to deduction of marks.

d. All coding questions should be answered using the C ++ syntax.

You are allowed to use the Dev-C++ compiler to write and test your code. If you do so please remember to copy and paste your code into the examination solution area. (Do NOT share your code)

**WARNING: Please note that Virtual University takes serious note of unfair means. Anyone found involved in cheating will get an `F` grade in this course.

For Teacher's use only Question 1 2 3 4 5 6 7 8 9 10 Total

Marks Question 11

Marks

Question No: 1 ( Marks: 10 )

Draw AVL Tree by following digits 15, 4, 13, 6, 17, 2, 11 and also perform necessary rotation,

Page 6: CS301 Collection of  Old Papers

while showing all the intermediate trees being created in the process. In each stage, the AVL transformation should be conducted at a discrepancy that is farthest from the root.

Question No: 2 ( Marks: 10 ) Some operations are given. Show the output of the given operations step by step in form of array. Enqueue(13); Enqueue(35); Enqueue(11); Enqueue(39); Enqueue(9); N = RemoveMin(); Enqueue( 51); N = RemoveMin(); Enqueue(15);

Question No: 3 ( Marks: 15 ) The frequency table for letters A, B, C, D and E is given Frequency Table

Character

Frequency Huffman Code

A 8 B 12 C 49 D 20 E 11

A) Create a Huffman tree to determine the binary codes for each character. (10) B) Fill the codes into the table above. (2.5) C) Encode the following sequence ABCDE. (2.5)

Question No: 4 ( Marks: 10 ) Following array is given which represents a min-heap. Insert 4 in the following array and convert it into a min-heap again. Show process steps by drawing heap trees.

33 55 99 66 88 120 110 122 180

Question No: 5 ( Marks: 10 ) Write down the C++ code to implement Bubble Sort Algorithm.

Page 7: CS301 Collection of  Old Papers

Question No: 6 ( Marks: 10 ) Create a hash table using hash table of size 10 i.e. (0-9). Insert the following values in the hash table 79, 76, 75, 56, 53, 47, 48, 63, 90 and 59. If there is any collision then insert a node in front of collision node to put the value in table e.g.

You are required to give answer in table form as shown above.

Question No: 7 ( Marks: 2 ) - Please choose one Which one is not Divide and Conquer algorithm? ►

merge sort

quick sort

heap sort

none of the above

Question No: 8 ( Marks: 2 ) - Please choose one Hash tables are very good if there are many insertions and deletions. ►

True

False

Question No: 9 ( Marks: 2 ) - Please choose one A table ts always a two dimensional array of same data type ►

True

► False

Page 8: CS301 Collection of  Old Papers

Question No: 10 ( Marks: 2 ) - Please choose one When there is a collision, we try to find some other place in our array. This approach is called ►

open addressing

closed hashing

open addressing & closed hashing

none of the above

Question No: 11 ( Marks: 2 ) - Please choose one ___________ is/are called nlog2n algorithm(s). ►

merge sort

quick sort

heap sort

all of the above

Page 9: CS301 Collection of  Old Papers

http://vujannat.ning.com BEST SITE TO HELP STUDENTS

MIDTERM EXAMINATION

FALL 2006

CS301 - DATA STRUCTURES (Session - 3 )

Marks: 40

Time: 60min

StudentID/LoginID: ______________________________

Student Name: ______________________________

Center Name/Code: ______________________________

Exam Date: Wednesday, December 06, 2006

1. Attempt all questions. Marks are written adjacent to each question.

2. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

c. Write all steps, missing steps may lead to deduction of marks.

d. All coding questions should be answered using the C ++ syntax.

You are allowed to use the Dev-C++ compiler to write and test your code. If you do so please remember to copy and paste your code into the examination solution area. (Do NOT share your code; your colleague could get higher marks than you!!)

**WARNING: Please note that Virtual University takes serious note of unfair means. Anyone found involved in cheating will get an `F` grade in this course.

For Teacher's use only Question 1 2 3 4 5 6 7 8 9 Total

Marks

Question No: 1 ( Marks: 2 ) - Please choose one The new operation in C++ for dynamically allocating memory returns a pointer to an object it has just created.

Page 10: CS301 Collection of  Old Papers

True

False

Question No: 2 ( Marks: 2 ) - Please choose one A pointer can be declared without giving it a data type to point to ►

True

False

Question No: 3 ( Marks: 2 ) - Please choose one An in-order traversal visits nodes in order of descending keys. ►

True

False

Question No: 4 ( Marks: 2 ) - Please choose one An unbalanced tree is one whose root has many more left descendents than right descendants. ►

True

False

Question No: 5 ( Marks: 2 ) - Please choose one A queue allows access to the first item that was inserted.

Page 11: CS301 Collection of  Old Papers

True

False

Question No: 6 ( Marks: 10 ) Write a function in C++ that will swap the second and third node in a singly linked list (having 5 nodes) by adjusting only the pointers (and not the data). You can use Node class and List class methods (such as getNext, setNext, next, get) without writing them. You can assume that the Node class and List class exists, i.e., do not write the code for these classes. The simple declaration of Node class and List class is as follow, class Node { public: int get() { return object; }; void set(int object) { this->object = object; }; Node * getNext() { return nextNode; }; //returns the next node pointer void setNext(Node * nextNode) { this->nextNode = nextNode; }; // set the next node pointer private: int object; Node * nextNode; }; /* The List class */ class List { public: List(); // constructor void add (int addObject); // add the nodes in list int get(); // returns the value of the current node bool next(); // returns true if next node exist otherwise returns false friend void traverse(List list); // used to print the values of all the nodes in the list void swap(); private: int size; Node * headNode; Node * currentNode; Node * lastCurrentNode; }; void List ::swap() // Complete this code { }

Question No: 7 ( Marks: 5 )

Page 12: CS301 Collection of  Old Papers

Write the output for the following Push the characters ‘c’, ‘d’, ‘m’, ‘a’, ‘b’ into the stack in the given order. Pop two elements from the stack one at a time. Then push two characters ‘f’, and ‘g’. Now pop all the characters. What is the result?

Question No: 8 ( Marks: 10 ) Convert the infix expression 2+(9-3 *2) to postfix. Show the trace of the algorithm, i.e., the stack, the infix expression and postfix expression using the following table pattern.

Stack infix postfix

Question No: 9 ( Marks: 5 ) Consider the following binary tree: (a) Starting from the root node A, perform an In-order traversal of the binary tree below and write the letters in the nodes that will result during the visitations. (b) Write the nodes if a Pre-order traversal is performed starting with node A.

A

B C

D E

F G

H

Page 13: CS301 Collection of  Old Papers
Page 14: CS301 Collection of  Old Papers

Page 1 of 3 WWW.vujannat.ning.com

http://vujannat.ning.com Largest Online Community of VU Students

CS301 Data Structures Final Term Examination - August 2004

Time Allowed: 150 Minutes

Please read the following instructions carefully before attempting any of the questions:

1. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no grade.

2. Attempt all questions. Marks are written adjacent to each question. 3. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

c. Wriite all steps, missing steps may lead to deduction of marks. 4. You are allowed to use any development environment like Dev C++ etc.

**WARNING: Please note that Virtual University takes serious note of unfair means. Anyone found involved in cheating will get an `F` grade in this course.

Total Marks: 135 Total Questions: 7 Question No. 1 Marks : 15

Consider the following Sort algorithms: Quicksort, Mergesort, Insertion Sort, Bubble Sort, Selection Sort

(a) Which is the fastest on an already sorted array? (b) Which do roughly the same amount of work regardless of the arrangement of the data values in the array? (c) Show the following array as it is sorted in ascending order, step by step, by insertion sort.

int[6] Arr = {3,2,7,9,1,6}; Question No. 2 Marks : 10

Consider the following binary tree:

(a) Starting from the root node A, perform a pre-order traversal of the binary tree below and write the letters in the nodes that will result during the visitations. (b) Write the nodes if an in-order traversal is performed starting with node A.

Question No. 3 Marks : 25

Consider the following problem: Given N elements in a data structure, find the middle element in sorted order. This is also called the median. Note the elements are not necessarily in sorted order unless the data structure forces them to be. For example, if the numbers are:

34 76 87 12 8 96 83 Then the middle element in sorted order is 76. If the elements had been sorted, 76 would be in the middle. For each of the following possible data structures assume the N elements are already in the data structure. For each data structure, describe briefly in one or two lines an efficient algorithm to find the middle element in sorted order (do not write code).

1. an unsorted array 2. a sorted linked list – (here the elements are already sorted) 3. a min heap 4. a balanced binary search tree 5. a hash table of size M

Question No. 4 Marks : 20

Using modulo 11 as the hash function "h(x) = x mod 11", show the contents of the hash table (indexed by 0..10) after the following values are stored in order: 3,14,25,4, 37. Show (pictorially) the result after each insertion. (a) Use linear probing to handle collisions.

(b) Use separate chaining to handle collisions.

Page 15: CS301 Collection of  Old Papers

Page 2 of 3 Question No. 5 Marks : 30

Consider the following piece of code: [30] class Employee { public: // Constructor functions Employee(); Employee(const string Name, const int Years, const float Salary, const bool Promote = True); string GetName () const; void GetAge (int &Age) const; float GetSalary() const; void Print() const; void SetName(const string Name); void SetAge(const int Age); void SetSalary(const float Pay); void SetPromotable(const bool Promote); private: bool getPromotability() const; string employeeName; int age; float salary; bool promotable; }; // Functions float ComputeAverageSalary (const Employee Workers[], const int NumWorkers) { float Sum = 0.0; for (int i = 0; i < NumWorkers; i++) { // CODE FRAGMENT 1 } return (Sum / NumWorkers); }; // Main program int main( ) { // INITIALIZATION CODE // CODE FRAGMENT 2 return 0; } a) Given these definitions above, determine which of the following are valid object creation examples? (Circle Valid or Invalid) (Valid / Invalid) Employee E2 ("", 0, 0.0); (Valid / Invalid) Employee E1 (Mohammed", 33, (float)40000, True); (Valid / Invalid) Employee E3 (E1); (Valid / Invalid) Employee E5 (33, 40000.0, True); (Valid / Invalid) Employee E4; b) Assume the Employee objects Amy and Bob have been properly created and initialized. Which of the following are valid object usage examples? (Circle Valid or Invalid) (Valid / Invalid) int Year = Bob.GetAge(); (Valid / Invalid) Bob.SetPromotable(bool True); (Valid / Invalid) Bob = Amy; (Valid / Invalid) Bob.SetName (Amy.GetName()); (Valid / Invalid) bool Promote = Bob.getPromotability(); c) Assume the Employee objects Bob and Amy have been properly created and initialized. Which of the following are valid object usage examples? (Circle Valid or Invalid) (Valid / Invalid) SetSalary(Bob, 35000); (Valid / Invalid) Print(Bob); (Valid / Invalid) Bob.SetAge(30); (Valid / Invalid) Amy.Print(); (Valid / Invalid) Amy.age = 23; d) How would you create an array of 30 Employee objects called Staff? a. You first must create a new class called EmployeeArray b. Employee Staff[30]; c. You cannot create an array of objects d. You must write a loop that executes 30 times to create the Employee objects e. none of the above. e) Consider CODE FRAGMENT 1. What code needs to go there? a. Sum += Employee.GetSalary(); b. Sum = Sum + Staff[i].GetSalary(); c. Sum += Workers[i].salary; d. Sum = Sum + Workers[i].GetSalary(); e. none of the above. f) In CODE FRAGMENT 2, how would you call ComputeAverageSalary() given an initialized array of 30 Employee objects called Staff. a. float Average = ComputeAverageSalary(Staff, 30); b. float Average = ComputeAverageSalary(Staff); c. float Average = Staff.ComputeAverageSalary(30); d. float Average = Staff.ComputeAverageSalary(NumWorkers); e. none of the above.

Question No. 6 Marks : 20

The following question applies to a Binary Search Tree (BST). [20] (a) Show the result of inserting (in order) 10,8,6,2,4,1,7 into an initially empty BST. Draw the diagram of resultant BST (b) Give an order in which the elements should arrive to have the worst case (largest) height, as well as the best case (minimum) height. (c) Give a linear time algorithm to determine if a BST is a valid BST. (d) Give a linear time algorithm to print all the nodes in a arbitrary tree in level order. That is, all nodes at depth 0 are printed first (the root) followed by nodes of depth 1, then depth 2 and so on.

Question No. 7 Marks : 15

Build an efficient Huffman tree using the algorithm we discussed in class for the following:

the cat in the hat

Show all steps in building the tree. The counts for each character have already been calculated for you. Also note the blank is represented by an underscore ( - ).

Page 16: CS301 Collection of  Old Papers

Page 3 of 3

Page 17: CS301 Collection of  Old Papers

In Stack we can access elements from both ends Question No. 3 Marks : 02

o False o True

In binary search tree (BST) every node has two or zero node.

Question No. 2 Marks : 02

o False o True

Queue is the LIFO structure.

Question No. 1 Marks : 02

Total Marks: 80 Total Questions: 11 5. You are allowed to use any development environment like Dev C++ etc.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

4. Do not ask any questions about the contents of this examination from anyone. 3. Unless stated otherwise, all questions carry a single mark.

2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no grade.

1. The duration of this examination is 150 Mins. Please read the following instructions carefully before attempting any question: Instructions

Time Allowed: 150 Minutes

Final Term Examination – Spring 2005

CS301 Data Structure

www.vujannat.ning.com

Page 18: CS301 Collection of  Old Papers

bool isEmpty(); binTree(); btnode* current; // current node in the bintree btnode* root; // root of the bintree public: class binTree {

Consider the following class definition for a binary tree of integers. [10 pts]

Question No. 8 Marks : 10

Insert 55, 35, 57, 25, 37, 56, 41, 39 elements into AVL tree that is initially empty; perform necessary rotation during insertion of elements. [10 pts]

Question No. 7 Marks : 10

c) Draw a BST that is as short as possible and contains the characters 'g', 'v', 'q', 'm', 'b'.

b) What will be the resulting tree after deleting the 'z', 't', 'h' in the given sequence.

a) Suppose the characters 'f', 'a', 'r','t', 'z', 'h', 'p', 'e', 'u', 'o' are stored in a Binary Search Tree (BST). draw a BST that contains these characters.

This question concerns trees containing character data. When two characters need to be compared, use normal alphabetic comparison, so that for example 'a' < 'g'. [15 pts]

Question No. 6 Marks : 15

o False o True

Every AVL is binary search tree (BST).

Question No. 5 Marks : 02

o False o True

Each node of linked list contains data element and pointer. Question No. 4 Marks : 02

o False o True

Page 19: CS301 Collection of  Old Papers

Question No. 10 Marks : 10

B) Fill the codes into the table above. A) Create a Huffman tree to determine the binary codes for each character. Y 4975 _ _ _ _ _ _ _ U 10324 _ _ _ _ _ _ _ O 25814 _ _ _ _ _ _ _ I 11552 _ _ _ _ _ _ _ E 45000 _ _ _ _ _ _ _ A 30676 _ _ _ _ _ _ _ character frequency Huffman code Frequency Table

A long sequence of vowels needs to be transmitted efficiently so a programmer decides to use Huffman encoding to encode the vowels. A distribution count study of typical data yielded the following frequency table. [10 pts]

Question No. 9 Marks : 10

} { bool completeTree(BinaryNode * rootNode)

Complete the C++ code that examine whether a tree is complete tree or not. (A binary tree is strictly binary tree or balance tree or complete tree if its every node has two children nodes (i.e. left node and right node) or zero child.)

};

bool isLeaf(); // True if this node is a leaf; false otherwise

btnode(int value); // Constructor public: binTree right; // right subtree binTree left; // left subtree int value; friend binTree; class btnode { };

int CountInterior(); //count the number of interior nodes

Page 20: CS301 Collection of  Old Papers

b. Draw a min-heap tree of the elements 67, 98, 115, 23, 45.

a. Remove the smallest element from the following array which represents a min-heap. [15 pts]

Question No. 10 Marks : 15

Using modulo 9 as the hash function "h(x) = x mod 9", show the contents of the hash table (indexed by 0...10) after the following values are stored in order: 5,11,25,40, 23. Use separate chaining to handle collisions. [10 pts]

Page 21: CS301 Collection of  Old Papers

WWW.vujannat.ning.Com Connecting VU Students

Question No. 3 Marks : 2

B) Create a Huffman tree from frequencies calc C) Fill the Huffman codes into the table above.

given above. ulated in part ‘A’ of this question.

into the table A) Calculate Frequency of each character from given string (“go go gopher”) and fill

Spa

s ----------- ----------- ce ----------- -----------

r ----------- ----------- e ----------- ----------- h ----------- ----------- p ----------- ----------- o ----------- ----------- g ----------- ----------- character frequency Huffman Co Frequency Table

des

S

Given the string "go go gophers". How Huffman coding is used to compress this

tring?

Question No. 2 Marks : 15

D. Float E. Choice (C) & (D)

C. IntegeB. String

r

A. Byte

Which of the following are primitive types?

Question No. 1 Marks : 2

Time Allowed: 150 MinutesFinal Term Examination – Spring 2006

CS301 Data Structure

Page 22: CS301 Collection of  Old Papers

True Tra ersing

show only two passes.

Hint: In step by step sorting you have to show passes for sorting, according to algorithm technique provided to yo

w

32,51,27,85,66,23,13,57 We apply Bubble sort algorithm to array ‘BS’.

Suppose the following digits are stored in an

rite down INORDER, PREORDER, POSTORDER Traversal of above described tree.

Question No. 5 Marks : 10

array ‘BS’:

Show step by step sorting. You have to rite only two passes that is pass 1 and pass 2.

u. There are 6 passes involved in sorting array ‘BS’. You have to

When inner loop complete its execution at once that is called one pass.

Question No. 6 Marks : 2

v a binary tree can only be done by a recursive algorithm.

False

Question No. 7 Marks : 5

W

31

21

6 16

9

11

15

Data Structure Node Link

Each entry in a linked list is called a _______

None of above

Question No. 4 Marks : 5

Page 23: CS301 Collection of  Old Papers

estion No. 10

value 86 into the heap. Draw the new heap tree when insertion is dB. Insert a new one.

A. Draw a tree diagram of the heap which is shown above.

Qu Marks : 2

49 97 76 61 42 54 59 31 23 17 44

. turestrueaps a senrep 11

uestion No. 9

if(*current == T)

for(; current != end

{

Ite

template < class Iter, class T >

What is wrong with the follow

reN2N1 = MFunc(T->left); if (T == NULL) return -1int N1, N2; { int MFunc (b typedef struct bt_s { i node of a binary tree.

llowing recursive “mystery” function computes when given a pointer to the root

nt key; struct bt_s *left, *right; } bt_t;

t_t *T)

;

= MFunc(T->right); turn (N1 > N2 ? N1 : N2) + 1;

}

Question No. 8 Marks : 5

ing implementation of code find?

r find (Iter current, Iter end, T elt)

; ++current)

return current;

}

Q Marks : 10

The following array of current size re t h c

1 2 3 4 5 6 7 8 9 10 11 12

Determine what the fo

Page 24: CS301 Collection of  Old Papers

wD

Question No. 12 Marks : 15

False

hashtableT

uestion No. 11 Mark

ve data structures non-linear data structures.... data types

Q s : 2

he constructor of the Hashtable class initializes data members and creates the .

True

raw an AVL Tree by following digits 1, 5, 6, 4, 18, 24 and also perform necessary rotation, hile showing all the intermediate trees being created in the process.

non-primiti primitive data structures

Stacks and queues are

Page 25: CS301 Collection of  Old Papers

WWW.vujannat.ning.comhttp://vujannat.ning.com

Largest Online Community of VU Students

MIDTERM EXAMINATION SEMESTER FALL 2003

CS301-DATA STRUCTURE

Total Marks:86 Duration: 60min

Instructions

Please read the following instructions carefully before attempting any question:

1. The duration of this examination is 60 Mins. 2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no

grade. 3. Unless stated otherwise, all questions carry a single mark. 4. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

5. Most, but not all, of the examination consists of multiple-choice questions. Choose only one choice as your answer.

a. If you believe that two (or more) of the choices are the correct ones for a particular question, choose the best one.

b. On the other hand, if you believe that all of the choices provided for a particular question are the wrong ones, select the one that appears to you as being the least wrong.

7. You are allowed to use any development environment like Dev C++ etc.

Page 26: CS301 Collection of  Old Papers

Question No: 1 Marks: 2

Here is the start of a class declaration: class Foo { public: void x(Foo f);

void y(const Foo f); void z(Foo f) const; ... Which of the three member functions can change the PRIVATE member variables of the Foo object that activates the function? a. Only x and y b. Only x and z c. Only y and z d. None of three the functions. e. All three functions. Question No: 2 Marks: 2

What is the common pattern of writing class definitions? a. Member functions and member variables are both private. b. Member functions are private, and member variables are public. c. Member functions are public, and member variables are private. d. Member functions and member variables are both public.

Question No: 3 Marks: 2

The Bag ADT is like the List ADT. The Bag ADT does not store items in any particular

order and it allows duplicates. Suppose that the Bag class is efficiently implemented with a fixed array with a capacity of 4000. Insert appends the new item at the end of the array. Choose the best description of b’s member variables size (count of items in the bag) and data (the array that holds the actual items) after we execute these statements:

Bag b; b.insert(5); b.insert(4); b.insert(6);

What will be the values of b.size and b.data after the statements? a. b.size is 3, b.data[0] is 4, b.data[1] is 5, b.data[2] is 6 b. b.size is 3, b.data[0] is 5, b.data[1] is 4, b.data[2] is 6 c. b.size is 3, b.data[0] is 6, b.data[1] is 4, b.data[2] is 5 d. b.size is 3, b.data[0] is 6, b.data[1] is 5, b.data[2] is 4

Question No: 4 Marks: 2

Page 27: CS301 Collection of  Old Papers

The operation for adding an entry to a stack is traditionally called: a. add b. append c. insert d. push

Question No: 5 Marks: 5

Consider the following pseudo code:

declare a stack of characters while ( there are more characters in the word to read ) {

read a character push the character on the stack

} while ( the stack is not empty ) {

pop a character off the stack write the character to the screen

}

What is written to the screen for the input “carpets”? a. serc b. carpets c. steprac d. ccaarrppeettss Question No: 6 Marks: 2

In the linked list implementation of the stack class, where does the push member function place the new entry on the linked list? a. At the head b. At the tail c. After all other entries that are greater than the new entry. d. After all other entries that are smaller than the new entry.

Question No: 7 Marks: 2

One difference between a queue and a stack is: a. Queues require dynamic memory, but stacks do not. b. Stacks require dynamic memory, but queues do not. c. Queues use two ends of the structure; stacks use only one. d. Stacks use two ends of the structure, queues use only one.

Question No: 8 Marks: 2

Page 28: CS301 Collection of  Old Papers

I have implemented the queue with a linked list, keeping track of a front pointer and a rear pointer. Which of these pointers will change during an insertion into a NONEMPTY queue? a. Neither changes b. Only front pointer changes. c. Only rear pointer changes. d. Both change.

Question No: 9 Marks: 2

I have implemented the queue with a linked list, keeping track of a front pointer and a rear pointer. Which of these pointers will change during an insertion into an EMPTY queue? a. Neither changes b. Only front pointer changes. c. Only rear pointer changes. d. Both change.

Question No: 10 Marks: 2

In a single function declaration, what is the maximum number of statements that may be recursive calls? a. 1 b. 2 c. n (where n is the argument) d. There is no fixed maximum

Question No: 11 Marks: 2

What is the maximum depth of recursive calls a function may make? a. 1 b. 2 c. n (where n is the argument) d. There is no fixed maximum

Question No: 12 Marks: 2

In which location do dynamic variables reside? a. The code segment. b. The data segment. c. The heap. d. The run-time stack

Question No: 13 Marks: 6

Page 29: CS301 Collection of  Old Papers

For public part of the Throttle declaration below, mark each function member header as

follows: • Mark C for any constructor; • mark X for any function that is forbidden from changing the throttles data fields.

class Throttle { public:

Throttle( ); Throttle(int size); void shut_off( ); void shift(int amount); double flow( ) const; bool is_on( ) const; ...

Answer/Solution class Throttle { public:

Throttle( ); C Throttle(int size); C void shut_off( ); void shift(int amount); double flow( ) const; X bool is_on( ) const;X ...

Question No: 14 Marks: 5

I am going to execute this code with THREE pushes and ONE pop: Stack s; s.push(1); s.push(2); s.push(3); cout << s.pop( );

Suppose that the stack s is represented by a fixed-sized array. Draw the state of the private member variables “data” and “top” of “s” after the above code:

Answer/Solution 0 1 2 3 4 5 6 7 8 9 1 2 Top 1

Question No: 15 Marks: 10

Page 30: CS301 Collection of  Old Papers

Complete the body of this function. Use a Queue of characters to store the input line as it is being read.

int counter( ) // Precondition: // There is a line of input waiting to be read from cin. // Postcondition: // A line of input has been read from cin, up to but not // including the newline character. The return value of // the function is the number of times that the LAST // character of the line appeared somewhere in this line. // EXAMPLE // Input: ABBXDXXZX The value returned by counter would // be 4 for this input since there are 4 X’s in // the input line.

{ int answer = 0; Queue q;

Answer/Solution int counter() { char a[100]; int i=0; int answer=0; Queue q; cin.getline(a,98,'\n'); for(i=0;i<strlen(a);i++) { q.enqueue(a[i]); } i--; while(!q.isEmpty()) { if(a[i]==q.dequeue()) { answer++; } } return answer; }

Question No: 16 Marks: 5

Page 31: CS301 Collection of  Old Papers

I am going to execute this code with THREE inserts and ONE remove: Queue s; s.insert(1); s.insert(2); s.insert(3); cout << s.remove();

Suppose that s is represented by a singly linked linked list. Draw the linked list and the state of the private member variables of s after the above code: front_ptr rear_ptr

Answer/Solution

Question No: 17 Marks: 10

Consider CList and Node classes defined as follows: class Node {

public: Node *next; Node *prev; int data;

}; class CList {

public: void insertHead(int); void insertTail(int); void removeHead(); void removeTail(); bool isEmpty(); bool find(int); private: Node *head; Node *tail;

}; A. write the body of the member function insertHead which inserts a new element at the head of the list.

void Clist::insertHead( int x ) {

B. write the body of the member function removeTail which removes the element at the tail of the list.

void Clist::removeTail( int x ) {

Front_prt

2 3

rear_prt

Page 32: CS301 Collection of  Old Papers

Answer/Solution (a) Solution for Question 17 option (a) void CList::insertHead(int x) { Node *newNode=new Node(); newNode->data=x; newNode->next=NULL; newNode->prev=NULL; if(isEmpty()) head=tail=newNode; else { newNode->next=head; newNode->prev=NULL; head->prev=newNode; head=newNode; } } (b) Solution for Question 17 option (b) void CList::removeTail(int &x) { if(isEmpty()) return; else { Node *p=tail; if(head==tail) head=tail=NULL; else { tail=tail->prev; tail->next=NULL; } x=p->data; delete p; return; }

}

Question No: 18 Marks: 10

Page 33: CS301 Collection of  Old Papers

Trace the running of the infix to postfix conversion algorithm on the infix expression (A - B) + C/D

Answer/Solution

Symbol Postfix Stack ( ( A A ( - A (- B AB (-

) AB- AB-

(

+ AB- + C AB-C + / AB-C +/

Question No: 19 Marks: 13

Here is a small binary tree:

A. What are all the leaves? (2pts) C. What are the ancestors of the node 10? (2pts) D. What are the descendants of the node 30? (2pts) E. Is the tree a binary search tree (BST) (true/false)? (2pts) F. Print the tree when visited in post-order manner? (5pts)

Answer/Solution A) Leaves of the tree = 1,3,7,40 B) Ancestors of the node 10 = 11,14 C) Descendants of the node 30 = 40 D) Is the tree a binary search tree (BST) (true/false) False E) Post Order Traversal = 1,3,2,7,10,40,30,11,14

Page 34: CS301 Collection of  Old Papers

WWW.vujannat.ning.comhttp://vujannat.ning.com

Largest Online Community of VU Students

MIDTERM EXAMINATION SEMESTER FALL 2003

CS301-DATA STRUCTURE

Total Marks:86 Duration: 60min

Instructions

Please read the following instructions carefully before attempting any question:

1. The duration of this examination is 60 Mins. 2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no

grade. 3. Unless stated otherwise, all questions carry a single mark. 4. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

5. Most, but not all, of the examination consists of multiple-choice questions. Choose only one choice as your answer.

a. If you believe that two (or more) of the choices are the correct ones for a particular question, choose the best one.

b. On the other hand, if you believe that all of the choices provided for a particular question are the wrong ones, select the one that appears to you as being the least wrong.

7. You are allowed to use any development environment like Dev C++ etc.

Page 35: CS301 Collection of  Old Papers

Question No: 1 Marks: 2

Is it possible for a member function of a class to activate another member function of the same class? a. No. b. Yes, but only public member functions. c. Yes, but only private member functions. d. Yes, both public and private member functions can be activated within another member function.

Question No: 2 Marks: 2

Consider this class definition: class quiz { public:

quiz( ); int f( ); int g( ) const;

private: double score;

}; Which functions can carry out an assignment score=1.0; to the private ember variable score? a. Both f and g can carry out the assignment. b. f can carry out the assignment, but not g. c. g can carry out the assignment, but not f. d. Neither f nor g can carry out the assignment Question No: 3 Marks: 2

In C++, when allocating an array of objects, what constructor is used to initialize all of the objects in the array? a. The automatic copy constructor. b. The constructor specified at the declaration. c. The default constructor. d. None of the above.

Question No: 4 Marks: 2

The list abstract data type (ADT) is used to work with ordered or unordered sequence of items such as numbers or strings. What of the following implementation of list ADT is best to answer questions such as "What is the item at position n?" a. Lists implemented with an array. b. Doubly-linked lists. c. Singly-linked lists. d. Doubly-linked or singly-linked lists are equally best

Question No: 5 Marks: 5

Page 36: CS301 Collection of  Old Papers

Consider this function declaration: void quiz(int i) { if (i > 1) { quiz(i / 2); quiz(i / 2); } cout << "*"; } How many asterisks are printed by the function call quiz(5)? a. 3 b. 4 c. 7 d. 8 e. Some other number Question No: 6 Marks: 2

Suppose T is a binary tree with 14 nodes. What is the minimum possible depth of T? a. 0 b. 3 c. 4 d. 5

Question No: 7 Marks: 2

“Entries in a stack are Ordered". What is the meaning of this statement? a. A collection of stacks can be sorted. b. Stack entries may be compared with the < operation. c. The entries must be stored in a linked list. d. There is a first entry, a second entry, and so on.

Question No: 8 Marks: 2

Which of the following applications may use a stack? a. A parentheses balancing program. b. Keeping track of local variables at run time. c. In-order traversal of a binary tree. d. All of the above.

Question No: 9 Marks: 2

Page 37: CS301 Collection of  Old Papers

When the compiler compiles your program, how is a recursive call treated differently than a non-recursive function call? a. Parameters are all treated as reference arguments b. Parameters are all treated as value arguments c. There is no duplication of local variables d. None of the above

Question No: 10 Marks: 2

What is the maximum depth of recursive calls a function may make? a. 1 b. 2 c. n (where n is the argument) d. There is no fixed maximum

Question No: 11 Marks: 2

In which location do dynamic variables reside? a. The code segment. b. The data segment. c. The heap. d. The run-time stack.

Question No: 12 Marks: 2

Select the one FALSE statement about binary trees: a. Every binary tree has at least one node. b. Every non-empty tree has exactly one root node. c. Every node has at most two children. d. Every non-root node has exactly one parent.

Question No: 13 Marks: 6

The nodes of a binary tree have data 1, 2, 3, 4. The in-order traversal of the tree yields 2,1,4,3. The postorder traversal is 2, 4, 3, 1. The root of the tree is at level 0.

Q1: In this binary tree, which value is at the root? (1 Pt)

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Q2: Which value is in the left child of the root? (1 Pt)

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Q3: Which value is in the right child of the root? (1 Pt)

Page 38: CS301 Collection of  Old Papers

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Q4: Which value is in a node at level 2 and is the left child of a node at level 1? (1.5 Pt)

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Q5: Which value is in a node at level 2 and is the right child of a node at level 1? (1.5 Pt)

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Question No: 14 Marks: 5

I am going to execute this code with THREE pushes and ONE pop: Stack s; s.push(1); s.push(2); s.push(3); cout << s.pop( );

Suppose that the stack s is represented by a fixed-sized array. Draw the state of the private member variables “data” and “top” of “s” after the above code:

Answer/Solution 0 1 2 3 4 5 6 7 8 9 1 2 Top 1

Question No: 15 Marks: 10

Complete the body of this function. Use a Queue of characters to store the input line as

it is being read. int counter( ) // Precondition: // There is a line of input waiting to be read from cin. // Postcondition: // A line of input has been read from cin, up to but not // including the newline character. The return value of // the function is the number of times that the LAST // character of the line appeared somewhere in this line. // EXAMPLE // Input: ABBXDXXZX The value returned by counter would // be 4 for this input since there are 4 X’s in // the input line.

{ int answer = 0; Queue q;

Answer/Solution

Page 39: CS301 Collection of  Old Papers

int counter() { char a[100]; int i=0; int answer=0; Queue q; cin.getline(a,98,'\n'); for(i=0;i<strlen(a);i++) { q.enqueue(a[i]); } i--; while(!q.isEmpty()) { if(a[i]==q.dequeue()) { answer++; } } return answer; }

Question No: 16 Marks: 5

I am going to execute this code with THREE inserts and ONE remove:

Queue s; s.insert(1); s.insert(2); s.insert(3); cout << s.remove();

Suppose that s is represented by a singly linked linked list. Draw the linked list and the state of the private member variables of s after the above code: front_ptr rear_ptr

Answer/Solution

Question No: 17 Marks: 10

Front_prt

2 3

rear_prt

Page 40: CS301 Collection of  Old Papers

A list is said to be sorted if the elements are in (say) increasing order, so {1, 2, 3, 3, 4, 4} is sorted whereas {1, 2, 3, 4, 3, 1} is not. A partial declaration for a singly-linked integer list class that keeps data in sorted order is as follows: class Node { public: int data; Node* next; Node(int d, Node *n) { data = d; next = n; } }; class intList { public: // ... // Remove any duplicate elements from the sorted list void removeDuplicates(); private: Node* head; // points to the first Node in the list // ... }; Give an implementation of the function removeDuplicates which removes any duplicate elements from the sorted list, so, for example {1, 2, 3, 3, 4, 4} would be reduced to {1, 2, 3, 4}. Answer/Solution // there a number of ways of doing this. Here is one. void intList::removeDuplicates() { Node* cur = head; Node *temp; Node* next = head != NULL? head->next : NULL; while( next != NULL ) { // delete next node if it has the same data as current node if( cur->data == next->data ) { temp=next; next = next->next; // cur stays where it is cur->next=next; delete temp;; } else { cur = next; // move to next pair next = cur->next; } } } Question No: 18 Marks: 10

Page 41: CS301 Collection of  Old Papers

Trace the running of the infix to postfix conversion algorithm on the infix expression A - ( B + C ) / D Answer/Solution

Symbol Postfix Stack A A - A - ( A - ( B AB - ( + AB - ( + C ABC - ( + ) ABC+

ABC+ - ( -

/ ABC+ - / D ABC+D - / ABC+D/-

Question No: 19 Marks: 13

Here is a small binary tree:

A. What are all the leaves? (2pts) C. What are the ancestors of the node 10? (2pts) D. What are the descendants of the node 30? (2pts) E. Is the tree a binary search tree (BST) (true/false)? (2pts) F. Print the tree when visited in post-order manner? (5pts)

Answer/Solution

A) Leaves of the tree = 1,3,7,40 B) Ancestors of the node 10 = 11,14 C) Descendants of the node 30 = 40 D) Is the tree a binary search tree (BST) (true/false) False E) Post Order Traversal = 1,3,2,7,10,40,30,11,14

Page 42: CS301 Collection of  Old Papers
Page 43: CS301 Collection of  Old Papers

WWW.vujannat.ning.comhttp://vujannat.ning.com

Largest Online Community of VU Students

MIDTERM EXAMINATION SEMESTER FALL 2003

CS301-DATA STRUCTURE

Total Marks:86 Duration: 60min

Instructions

Please read the following instructions carefully before attempting any question:

1. The duration of this examination is 60 Mins. 2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no

grade. 3. Unless stated otherwise, all questions carry a single mark. 4. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

5. Most, but not all, of the examination consists of multiple-choice questions. Choose only one choice as your answer.

a. If you believe that two (or more) of the choices are the correct ones for a particular question, choose the best one.

b. On the other hand, if you believe that all of the choices provided for a particular question are the wrong ones, select the one that appears to you as being the least wrong.

7. You are allowed to use any development environment like Dev C++ etc.

Page 44: CS301 Collection of  Old Papers

Question No: 1 Marks: 2

Given the class declaration

class MyClass {

public: ... void Func(); private: int n;

};

what notation does the body of Func use to assign the value 3 to n? (a) n = 3; (b) MyClass.n = 3; (c) MyClass::n = 3; (d) someObject.n = 3; (d) It can’t be done–n is private. Question No: 2 Marks: 2

Suppose that the class declaration of SomeClass includes the following function prototype.

bool LessThan( SomeClass anotherObject ); Which of the following tests in the client code correctly compares two class objects alpha and beta? (a) if (alpha < beta) (b) if (alpha.LessThan(beta)) (c) if (LessThan(alpha, beta)) (d) if (alpha.LessThan.beta) (e) if (LessThan(alpha).beta) Question No: 3 Marks: 2

When should you use a const reference parameter? (a) Whenever the data type might be many bytes. (b) Whenever the data type might be many bytes, the function changes the parameter within its body, and you do NOT want these changes to alter the actual argument. (c) Whenever the data type might be many bytes, the function changes the parameter within its body, and you DO want these changes to alter the actual argument. (d) Whenever the data type might be many bytes, and the function does not change the

parameter within its body.

Question No: 4 Marks: 2

Page 45: CS301 Collection of  Old Papers

The Bag ADT is like the List ADT. The Bag ADT does not store items in any particular order and it allows duplicates. Suppose that the Bag class is efficiently implemented with a fixed array with a capacity of 4000. Insert appends the new item at the end of the array. Choose the best description of b’s member variables size (count of items in the bag) and data (the array that holds the actual items) after we execute these statements:

Bag b; b.insert(5); b.insert(4); b.insert(6);

What will be the values of b.size and b.data after the statements? (a) b.size is 3, b.data[0] is 4, b.data[1] is 5, b.data[2] is 6 (b) b.size is 3, b.data[0] is 5, b.data[1] is 4, b.data[2] is 6 (c) b.size is 3, b.data[0] is 6, b.data[1] is 4, b.data[2] is 5 (d) b.size is 3, b.data[0] is 6, b.data[1] is 5, b.data[2] is 4 Question No: 5 Marks: 2

The operation for removing an entry from a stack is traditionally called: (a) delete (b) peek (c) pop (d) remove

Question No: 6 Marks: 2

Which of the following stack operations could result in stack underflow? (a) is empty (b) pop (c) push (d) Two or more of the above answers

Question No: 7 Marks: 5

Consider the following pseudo code:

declare a stack of characters while ( there are more characters in the word to read ) {

read a character push the character on the stack

} while ( the stack is not empty ) {

pop a character off the stack write the character to the screen

}

Page 46: CS301 Collection of  Old Papers

What is written to the screen for the input “carpets”? (a) serc (b) carpets (c) steprac (d) ccaarrppeettss

Question No: 8 Marks: 2

In the linked list implementation of the stack class, where does the push member function place the new entry on the linked list? (a) At the head (b) At the tail (c) After all other entries that are greater than the new entry. (d) After all other entries that are smaller than the new entry.

Question No: 9 Marks: 2

Given a stack of n items, how many POP and PUSH operations need to be performed to remove the item at its bottom? (a) 0 POP operation and 0 PUSH operation (b) 1 POP operation and 1 PUSH operation (c) n POP operations and n PUSH operations (d) n POP operations and n-1 PUSH operations (e) Unknown Question No: 10 Marks: 2

In the linked list implementation of the queue class, where does the insert member function place the new entry on the linked list? (a) At the head (b) At the tail (c) After all other entries that are greater than the new entry. (d) After all other entries that are smaller than the new entry.

Question No: 11 Marks: 2

Page 47: CS301 Collection of  Old Papers

I have implemented the queue with a linked list, keeping track of a front pointer and a rear pointer. Which of these pointers will change during an insertion into a NONEMPTY queue? (a) Neither changes (b) Only front pointer changes. (c) Only rear pointer changes. (d) Both change.

Question No: 12 Marks: 2

I have implemented the queue with a linked list, keeping track of a front pointer and a rear pointer. Which of these pointers will change during an insertion into an EMPTY queue? (a) Neither changes (b) Only front pointer changes. (c) Only rear pointer changes. (d) Both change.

Question No: 13 Marks: 6

For public part of the Throttle declaration below, mark each function member header as follows:

• Mark C for any constructor; • mark X for any function that is forbidden from changing the throttles data fields. class Throttle {

public: Throttle( ); Throttle(int size); void shut_off( ); void shift(int amount); double flow( ) const; bool is_on( ) const; ...

Answer/Solution class Throttle {

public: Throttle( ); C Throttle(int size); C void shut_off( ); void shift(int amount); double flow( ) const; X bool is_on( ) const; X ...

Question No: 14 Marks: 5

Page 48: CS301 Collection of  Old Papers

I am going to execute this code with THREE pushes and ONE pop:

Stack s; s.push(1); s.push(2); s.push(3); cout << s.pop( );

Suppose that the stack s is represented by a singly linked list. Draw the linked list after the above operations and show where the top element is in the list. head --> Answer/Solution

Question No: 15 Marks: 10

Complete the body of this function. Use a Queue of characters to store the input line as it is being read.

int counter( ) // Precondition: // There is a line of input waiting to be read from cin. // Postcondition: // A line of input has been read from cin, up to but not // including the newline character. The return value of // the function is the number of times that the LAST // character of the line appeared somewhere in this line. // EXAMPLE // Input: PQQYDYYTY // The value returned by the function counter would // be 4 for this input since there are 4 Y’s in // the input line. {

int answer = 0; Queue q;

Answer/Solution int counter() { char a[100]; int i=0; int answer=0; Queue q; cin.getline(a,98,'\n'); for(i=0;i<strlen(a);i++) { q.enqueue(a[i]); } i--; while(!q.isEmpty())

2 1 head

Page 49: CS301 Collection of  Old Papers

{ if(a[i]==q.dequeue()) { answer++; } } return answer; }

Question No: 16 Marks: 5

. I am going to execute this code with THREE inserts (enqueue) and ONE remove ( dequeue ):

Queue s; s.insert(1); s.insert(2); s.insert(3); cout << s.remove( );

Suppose that queue s is represented by a circular array. Draw the state of the private member variables “data” and “front” of s after the above code:

Answer/Solution

0 1 2 3 4 5 6 7 8 9 2 3 Front 1

Question No: 17 Marks: 10

Page 50: CS301 Collection of  Old Papers

Consider CList and Node classes defined as follows:

class Node {

public: Node *next; Node *prev; int data;

}; class CList {

public: void insertHead(int); void insertTail(int); void removeHead(); void removeTail(); bool isEmpty(); bool find(int); private: Node *head; Node *tail;

}; A. write the body of the member function insertHead which inserts a new element at the head of the list.

void Clist::insertHead( int x ) {

B. write the body of the member function removeTail which removes the element at the tail of the list.

void Clist::removeTail( int x ) {

Answer/Solution (a) Solution for Question 17 option (a) void CList::insertHead(int x) { Node *newNode=new Node(); newNode->data=x; newNode->next=NULL; newNode->prev=NULL; if(isEmpty()) head=tail=newNode; else { newNode->next=head; newNode->prev=NULL; head->prev=newNode; head=newNode; } } (b) Solution for Question 17 option (b) void CList::removeTail(int &x) { if(isEmpty())

Page 51: CS301 Collection of  Old Papers

return; else { Node *p=tail; if(head==tail) head=tail=NULL; else { tail=tail->prev; tail->next=NULL; } x=p->data; delete p; return; } }

Question No: 18 Marks: 10

Trace the running of the infix to postfix conversion algorithm on the infix expression A * (B − C)/D

A * ( B – C ) / D

Symbol Postfix Stack A A * A * ( A *( B AB *( - AB *(- C ABC *(- ) ABC-

ABC- *( *

Page 52: CS301 Collection of  Old Papers

/ ABC-* / D ABC-*D ABC-*D/

Question No: 19 Marks: 13

Here is a small binary tree:

A. What are all the leaves? (2pts) C. What are the ancestors of the node 30?(2pts) D. What are the descendants of the node 11? (2pts) E. Is the tree a binary search tree (BST) (true/false)? (2pts) F. Print the tree when visited in in-order manner? (5pts)

Answer/Solution

A) Leaves of the Tree = 1,3,7,40 B) Ancestors of the node 30 = 11,14 C) Descendants of the node 11= 10,30,7,40 D) Is the three a binary search tree (BST) (True/False) False E) In-order Traversal = 1,2,3,14,7,10,11,30,40

Page 53: CS301 Collection of  Old Papers

5 Linker error 4 Compiler error 3 Problem with computer 2 Logical error 1 Syntax error

If a program is producing incorrect results on execution, it means there is a:

Question No. 1 Marks : 2

Total Marks: 100 Total Questions: 11

**WARNING: Please note that Virtual University takes serious note of unfair means. Anyone found involved in cheating will get an `F` grade in this course.

You are allowed to use the Dev-C++ compiler to write and test your code. If you do so please remember to copy and paste your code into the examination solution area. (Do NOT share your code; your colleague could get higher marks than you!!)

d. All coding questions should be answered using the C ++ syntax. c. Write all steps, missing steps may lead to deduction of marks.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

2. Do not ask any questions about the contents of this examination from anyone.

1. Attempt all questions. Marks are written adjacent to each question.

Please read the following instructions carefully before attempting any of the questions:

Time Allowed: 90 MinutesMid Term Examination - November 2004

www.vujannat.ning.com CS201 Introduction to Programming

Page 54: CS301 Collection of  Old Papers

4 seekg () 3 get () 2 read () 1 open ()

fstream, ifstream and ofstream open a file with:

Question No. 7 Marks : 2

What is a pointer? What is call by value and call by reference? Briefly explain with examples.

Question No. 6 Marks : 6

5 int* yourptr, myptr; 4 int * myptr; 3 *int myptr; 2 int myptr; 1 int pointer myptr;

Which one is the correct declaration for a pointer myptr to an integer?

Question No. 5 Marks : 2

5 always appears on the screen 4 is written in C language only 3 is a precise sequence of steps to solve a particular problem 2 is a plan for a picnic 1 writes a document in word processor

A computer program:

Question No. 4 Marks : 2

5 Only pointers 4 Variables of different data types 3 native data types and can not have pointers 2 Only integers 1 Variables of one type of data only

In a structure we have

Question No. 3 Marks : 2

Write a program that asks the user to enter two numbers, obtains the two numbers from the user, and prints the sum, product, difference, quotient and modulus of the two numbers.

Question No. 2 Marks : 8

Page 55: CS301 Collection of  Old Papers

Write a function which displays first 100 ints, starting from 1, using for loop?

Question No. 11 Marks : 4

Also write the bill details (cost of each Item and total bill) in a text file called "BillDetail.txt".

Total (15% discount if above 850) 990.25 Software 4 50.00 200.00 Printer 1 75.00 75.00 Disk Drive 2 200.00 400.00 PC 1 490.00 490.00 Item Quantity Price Cost The Super Cheap Computer Company Number of Software Packages: Number of Printers: Number of Disk Drives: Number of PCs:

Please enter the following info:

The Super Cheap Computer Company sells its product, the Super-Cheap-PC, for Rs.490.00. In addition, they sell disk drives for Rs.200.00, printers for Rs.75.00 and software packages for Rs.50.00 each. If the customer's total bill would be above Rs.850.00 then the customer gets a 15% discount. Write a program that prompts the salesperson to enter quantity of each item the customer wants to purchase and then outputs a bill. The complete interactive I/O should appear as below:

Question No. 10 Marks : 14

5 Can not execute infinitely 4 Consists one and only one statement 3 Can not be executed more than100 times 2 Executes zero or more times 1 Executes at least once

The body of for loop

Question No. 9 Marks : 2

Write a function that shows max of 3 numbers entered by user?

Question No. 8 Marks : 6

5 seekp ()

Page 56: CS301 Collection of  Old Papers

WWW.vujannat.ning.COM Connecting VU Students

MIDTERM EXAMINATION

FALL 2006

CS301 - DATA STRUCTURES (Session - 3 )

Marks: 40

Time: 60min

StudentID/LoginID: ______________________________

Student Name: ______________________________

Center Name/Code: ______________________________

Exam Date: Wednesday, December 06, 2006

1. Attempt all questions. Marks are written adjacent to each question.

2. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

c. Write all steps, missing steps may lead to deduction of marks.

d. All coding questions should be answered using the C ++ syntax.

You are allowed to use the Dev-C++ compiler to write and test your code. If you do so please remember to copy and paste your code into the examination solution area. (Do NOT share your code; your colleague could get higher marks than you!!)

**WARNING: Please note that Virtual University takes serious note of unfair means. Anyone found involved in cheating will get an `F` grade in this course.

For Teacher's use only Question 1 2 3 4 5 6 7 8 9 Total

Marks Question No: 1 ( Marks: 2 ) - Please choose one

Page 57: CS301 Collection of  Old Papers

The new operation in C++ for dynamically allocating memory returns a pointer to an object it has just created. ►

True

False

Question No: 2 ( Marks: 2 ) - Please choose one A pointer can be declared without giving it a data type to point to ►

True

False

Question No: 3 ( Marks: 2 ) - Please choose one An in-order traversal visits nodes in order of descending keys. ►

True

False

Question No: 4 ( Marks: 2 ) - Please choose one An unbalanced tree is one whose root has many more left descendents than right descendants. ►

True

► False

Page 58: CS301 Collection of  Old Papers

Question No: 5 ( Marks: 2 ) - Please choose one A queue allows access to the first item that was inserted. ►

True

False

Question No: 6 ( Marks: 10 ) Write a function in C++ that will swap the second and third node in a singly linked list (having 5 nodes) by adjusting only the pointers (and not the data). You can use Node class and List class methods (such as getNext, setNext, next, get) without writing them. You can assume that the Node class and List class exists, i.e., do not write the code for these classes. The simple declaration of Node class and List class is as follow, class Node { public: int get() { return object; }; void set(int object) { this->object = object; }; Node * getNext() { return nextNode; }; //returns the next node pointer void setNext(Node * nextNode) { this->nextNode = nextNode; }; // set the next node pointer private: int object; Node * nextNode; }; /* The List class */ class List { public: List(); // constructor void add (int addObject); // add the nodes in list int get(); // returns the value of the current node bool next(); // returns true if next node exist otherwise returns false friend void traverse(List list); // used to print the values of all the nodes in the list void swap(); private: int size; Node * headNode; Node * currentNode;

Page 59: CS301 Collection of  Old Papers

Node * lastCurrentNode; }; void List ::swap() // Complete this code { } Question No: 7 ( Marks: 5 ) Write the output for the following Push the characters ‘c’, ‘d’, ‘m’, ‘a’, ‘b’ into the stack in the given order. Pop two elements from the stack one at a time. Then push two characters ‘f’, and ‘g’. Now pop all the characters. What is the result? Question No: 8 ( Marks: 10 ) Convert the infix expression 2+(9-3 *2) to postfix. Show the trace of the algorithm, i.e., the stack, the infix expression and postfix expression using the following table pattern.

Stack infix postfix

Question No: 9 ( Marks: 5 ) Consider the following binary tree: (a) Starting from the root node A, perform an In-order traversal of the binary tree below and write the letters in the nodes that will result during the visitations. (b) Write the nodes if a Pre-order traversal is performed starting with node A.

Page 60: CS301 Collection of  Old Papers

A

B C

D E

F G

H

Page 61: CS301 Collection of  Old Papers

WWW.vujannat.ning.comhttp://vujannat.ning.com

Largest Online Community of VU Students Virtual University Government of Pakistan

Midterm Examination Spring 2003

Data Structure (CS301)

StudentID/LoginID Name PVC Name/Code Date April 26, 2003

Instructions Please read the following instructions carefully before attempting any question:

1. The duration of this examination is 90 Mins.

2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no grade.

3. For multiple choice questions, you will lose 1/4 of the points for a wrong answer. However, if you select nothing then it will not be counted as a wrong answer.

4. Unless stated otherwise, all questions carry a single mark.

5. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

6. Most, but not all, of the examination consists of multiple-choice questions. Choose only one choice as your answer.

Page 62: CS301 Collection of  Old Papers

a. If you believe that two (or more) of the choices are the correct ones for a particular question, choose the best one.

b. On the other hand, if you believe that all of the choices provided for a particular question are the wrong ones, select the one that appears to you as being the least wrong.

7. You are not allowed to use any development environment like Dev C++ etc.

CS301-Data Structure

Time allowed: 90 minutes Max Marks: 33

Question 1: [1 pt] Here is the start of a C++ class declaration: class foo { public: void x(foo f); void y(const foo f); void z(foo f) const; ... Which of the three member functions can alter the PRIVATE member variables of the foo object that activates the function?

A. Only x can alter the private member variables of the object that activates the function. B. Only y can alter the private member variables of the object that activates the function. C. Only z can alter the private member variables of the object that activates the function. D. Two of the functions can alter the private member variables of the object that activates the function. E. All of the functions can alter the private member variables of the object that activates the function.

Question 2: [1 pt] In C++, when allocating an array of objects, what constructor is used to initialize all of the objects in the array?

A. The automatic copy constructor. B. The constructor specified at the declaration. C. The default constructor. D. None of the above.

Question 3: [1 pt] The list abstract data type (ADT) is used to work with ordered or unordered sequence of items such as numbers or strings. What of the following implementation of list ADT is best to answer questions such as "What is the item at position n?"

Page 63: CS301 Collection of  Old Papers

A. Lists implemented with an array. B. Doubly-linked lists. C. Singly-linked lists. D. Doubly-linked or singly-linked lists are equally best

Question 4: [1 pt] Which of the following stack operations could result in stack underflow?

A. is_empty B. pop C. push D. Two or more of the above answers

Question 5: [1 pt] One difference between a queue and a stack is:

A. Queues require dynamic memory, but stacks do not. B. Stacks require dynamic memory, but queues do not. C. Queues use two ends of the structure; stacks use only one. D. Stacks use two ends of the structure, queues use only one.

Question 6: [1 pt] What is the maximum depth of recursive calls a function may make?

A. 1 B. 2 C. n (where n is the argument) D. There is no fixed maximum

Question 7: [1 pt] Consider this function declaration: void quiz(int i) { if (i > 1) { quiz(i / 2); quiz(i / 2); } cout << "*"; } How many asterisks are printed by the function call quiz(5)?

Page 64: CS301 Collection of  Old Papers

A. 3 B. 4 C. 7 D. 8 E. Some other number

Question 8: [1 pt] Suppose T is a binary tree with 14 nodes. What is the minimum possible depth of T?

A. 0 B. 3 C. 4 D. 5

Question 9: [6 pts] The nodes of a binary tree have data 1, 2, 3, 4. The in-order traversal of the tree yields 2,1,4,3. The postorder traversal is 2, 4, 3, 1. The root of the tree is at level 0.

Q1: In this binary tree, which value is at the root? (1 Pt)

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Q2: Which value is in the left child of the root? (1 Pt)

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Q3: Which value is in the right child of the root? (1 Pt)

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Q4: Which value is in a node at level 2 and is the left child of a node at level 1? (1.5 Pt)

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Q5: Which value is in a node at level 2 and is the right child of a node at level 1? (1.5 Pt)

(A) 1 (B) 2 (C) 3 (D) 4 (E) none

Question 10: [10 pts] A list is said to be sorted if the elements are in (say) increasing order, so {1, 2, 3, 3, 4, 4} is sorted whereas {1, 2, 3, 4, 3, 1} is not. A partial declaration for a singly-linked integer list class that keeps data in sorted order is as follows:

Page 65: CS301 Collection of  Old Papers

class Node { public: int data; Node* next; Node(int d, Node *n) { data = d; next = n; } }; class intList { public: // ... // Remove any duplicate elements from the sorted list void removeDuplicates(); private: Node* head; // points to the first Node in the list // ... }; Give an implementation of the function removeDuplicates which removes any duplicate elements from the sorted list, so, for example {1, 2, 3, 3, 4, 4} would be reduced to {1, 2, 3, 4}.

Question 11: [10 pts] Trace the running of the infix to postfix conversion algorithm on the infix expression

(A+B)−C/D symbol postfix string operator stack

Page 66: CS301 Collection of  Old Papers
Page 67: CS301 Collection of  Old Papers

WWW.vujannat.ning.comhttp://vujannat.ning.com

Largest Online Community of VU Students Virtual University Government of Pakistan

Midterm Examination Spring 2003

Data Structure (CS301)

StudentID/LoginID Name PVC Name/Code Date April 26, 2003

Instructions Please read the following instructions carefully before attempting any question:

1. The duration of this examination is 90 Mins.

2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no grade.

3. For multiple choice questions, you will lose 1/4 of the points for a wrong answer. However, if you select nothing then it will not be counted as a wrong answer.

4. Unless stated otherwise, all questions carry a single mark.

5. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

6. Most, but not all, of the examination consists of multiple-choice questions. Choose only one choice as your answer.

Page 68: CS301 Collection of  Old Papers

a. If you believe that two (or more) of the choices are the correct ones for a particular question, choose the best one.

b. On the other hand, if you believe that all of the choices provided for a particular question are the wrong ones, select the one that appears to you as being the least wrong.

7. You are not allowed to use any development environment like Dev C++ etc.

CS301-Data Structure

Time allowed: 90 minutes Max Marks: 33

Question 1: [1 pt] In C++, when should you use a const reference parameter?

A. Whenever the data type might be many bytes. B. Whenever the data type might be many bytes, the function changes the parameter within its body, and you do NOT want these changes to alter the actual argument. C. Whenever the data type might be many bytes, the function changes the parameter within its body, and you DO want these changes to alter the actual argument. D. Whenever the data type might be many bytes, and the function does not change the parameter within its body.

Question 2: [1 pt] In C++, in which location in memory do dynamic variables (allocated with new) reside?

A. The code segment. B. The data segment. C. The heap. D. The run-time stack.

Question 3: [1 pt] “Entries in a stack are Ordered". What is the meaning of this statement?

A. A collection of stacks can be sorted. B. Stack entries may be compared with the < operation. C. The entries must be stored in a linked list. D. There is a first entry, a second entry, and so on.

Question 4: [1 pt] Which of the following applications may use a stack?

A. A parentheses balancing program. B. Keeping track of local variables at run time.

Page 69: CS301 Collection of  Old Papers

C. In-order traversal of a binary tree. D. All of the above.

Question 5: [1 pt] If the characters 'D', 'C', 'B', 'A' are placed in a queue (in that order), and then removed one at a time, in what order will they be removed?

A. ABCD B. ABDC C. DCAB D. DCBA

Question 6: [1 pt] When the compiler compiles your program, how is a recursive call treated differently than a non-recursive function call?

A. Parameters are all treated as reference arguments B. Parameters are all treated as value arguments C. There is no duplication of local variables D. None of the above

Question 7: [1 pt] When a function call is executed, which information is not saved in the call stack?

A. Current depth of recursion. B. Formal parameters. C. Location where the function should return when done. D. Local variables.

Question 8: [1 pt] Select the one FALSE statement about binary trees:

A. Every binary tree has at least one node. B. Every non-empty tree has exactly one root node. C. Every node has at most two children. D. Every non-root node has exactly one parent.

Question 9: [5 pts] Consider the following binary search tree. 5 / 2 / \

Page 70: CS301 Collection of  Old Papers

1 4 / 3 The value 5 is removed from the tree. The following questions refer to BST that remains after 5 has been removed. The root is at level 0.

Q1: Which value is placed in the root?

(A) 1 (B) 2 (C) 3 (D) 4 (E) 5

Q2: Which value is at level 2?

(A) 1 (B) 2 (C) 3 (D) 4 (E) 5

Q3: Which value is level 1?

(A) 1 (B) 2 (C) 3 (D) 4 (E) 5

Q4: How many values are moved up the tree?

(A) 1 (B) 2 (C) 3 (D) 4 (E) 5

Question 10: [10 pts] A singly linked list containing integers is stored in the memory of the computer. A node of the list contains an integer and a next pointer. The last node's next pointer is NULL. The pointer variable head points to the first node in the list. Here is the picture of the list in memory.

544 496 540 8 536 540 532 2 528 508 524 7 520 516 512 0 508 6

head 504 532 500 524 496 1 494

Page 71: CS301 Collection of  Old Papers

Each location is four bytes which is why the memory addresses on the left of the memory cells increase by 4. The integer data is shown in the memory cells. The cell right above the data cell is the next pointer. For example, the list item '2' is stored at location 532 and its next pointer is at location 536. The list node, thus, made up of the two cells: 532 and 536. The head variable itself is in memory at location 504. Draw the singly linked list with nodes and arrows showing the order of the nodes and the links between them.

Question 11: [10 pts] Trace the running of the infix to postfix conversion algorithm on the infix expression

A+(B−C)/D

Symbol Postfix

string Operator stack

Page 72: CS301 Collection of  Old Papers

WWW.vujannat.ning.com http://vujannat.ning.com

Largest Online Community of VU Students H

MIDTERM EXAMINATION SEMESTER SPRING 2004 CS301-DATA STRUCTURE

Total Marks:75 Duration: 60min

Instructions

Please read the following instructions carefully before attempting any question:

1. The duration of this examination is 60 Mins. 2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no

grade. 3. Unless stated otherwise, all questions carry a single mark. 4. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

5. You are allowed to use any development environment like Dev C++ etc.

Page 73: CS301 Collection of  Old Papers

Question No: 1 Marks: 5

What is the value of the C/C++ expression: 6.2 + 5 / 3 Answer: 6.2+5/3 6.2+1 (As 5 & 3 are integers so result will be in integer, fraction portion will be discard) 7.2 Question No: 2 Marks: 5

What is the value of the postfix expression: 8 6 4 + 3 * + 5 + Answer:

Input op1 op2 value stack 8 8 6 6

8 4 4

6 8

+ 6 4 10 10 8

3 3 10 8

* 10 3 30 30 8

+ 8 30 38 38 5 5

38 + 38 5 43 43

Value of Postfix Expression = 43 Question No: 3 Marks: 5

Write an equivalent postfix expression for the infix expression:

6 + ( 5 - 3 ) * 8

assuming standard precedence for order of operations. Answer: 6 5 3 - 8 * +

Step No. Symbol Postfix Stack 1 6 2 + 6 + 3 ( 6 +(

Page 74: CS301 Collection of  Old Papers

4 5 6 5 +( 5 - 6 5 +(- 6 3 6 5 3 +(- 7 ) 6 5 3 - + 8 * 6 5 3 - +* 9 8 6 5 3 - 8 +* 10 6 5 3 - 8 * +

Question No: 4 Marks: 10

A linked list node class is declared as follow: class Node { public: Node(const string& s, Node* ptr) : info(s), next(ptr) { } private: string info; Node* next; }; Write a function that changes every ’t’ that occurs as the first letter of a word to a ’b’. No other letters should change. For example, ("tin", "tile", "ant", "saint", "tot") should be changed to ("bin", "bile", "ant", "saint", "bot") void change(Node* list) // post condition: all t’s that occur as first letters of a // word in the list nodes are changed to b’s { Answer: Void change(Node * list) { temp = list; While(temp !=NULL) { If (temp->info[0]==’t’) Info[0]=’b’; Temp=temp->next; } //end of while } Question No: 5 Marks: 15

Page 75: CS301 Collection of  Old Papers

The tree below is a binary search tree.

a) What is the preorder traversal of the tree? b) Add nodes containing “black” and “panda” so that the tree remains a search tree. Add “black” first. Draw the nodes attached to the tree diagram above. c) Draw a search tree in which “teddy” is at the root of the tree, and the root’s left child is “polar” (include all other nodes from the tree in the diagram above, these other nodes can occur in any order in the tree you draw.) Answer

a) grizzly, brown, polar, koala, teddy b) grizzl / \ brown polar / / \ black koala teddy \ panda c) teddy / polar / grizzly / \ brown koala

Question No: 6 Marks: 10

Draw a box and pointer diagram (i.e., a linked list) of what list points to after executing the following code fragment: string* name; Stack<string*> s; Node* list = NULL; s.push(new string("Naveed")); s.push(new string("Mahmood")); s.push(new string("Mohsin")); s.push(new string("Aijaz"));

Page 76: CS301 Collection of  Old Papers

s.push(new string("Pervaiz")); while (!s.empty()) { name = s.pop(name); list = new Node(name, list); } Answer:

Question No: 7 Marks: 5

Consider the following Mystery function. int Mystery(int num) { if (num > 4) { return 2 + Mystery(num - 5) + Mystery(num - 2); } return 1; } What is the value returned from the call Mystery(5)? Answer: 4 Question No: 8 Marks: 20

In the syntax of most programming languages, there are some characters that occur only in nested pairs, which are called bracketing operators. C++ has the following bracketing operators: ( ::: ) [ ::: ] {::: } In a properly formed program, these characters will be properly nested and matched. To determine whether this condition holds for a particular program, you can ignore all the other characters and look

Page 77: CS301 Collection of  Old Papers

simply at the pattern formed by the parentheses, brackets, and braces. In a legal configuration, all the operators match up correctly, as shown in the following example:

{ x = ( s = v[ 1 ] + 2 ); y = 4 * ( v [ v.size() - 1 ] + x ); } The following configurations are illegal for the reasons stated:

• ( ( [ 4 ] )The line is missing a close parenthesis. • AB) ( The close parenthesis comes before the open parenthesis. • {( x} ) The parentheses and curly braces are improperly nested.

For this problem, your task is to write a function bool isBalanced(string s) that takes a string s with all characters except the bracketing operators removed. For example, for the program statements

{ x = ( s = v [ 1 ] + 2 ); y = 4 * ( v [ v.size() - 1 ] + x ); } The string s would contain

{ ( [ ] ) ( [ ( ) ] ) }

The method should return true if the bracketing operators in s are balanced, which means they are correctly nested and aligned, otherwise it should return false. You must either use a Stack or recursion in your solution. Assume you have the following helper functions. bool IsOpener(char ch); // returns true if ch is ( { or [, else false bool IsCloser(char ch); // returns true if ch is ) } or ], else false char MatchingChar(char ch); // returns matching char. // In other words, returns { for }, // } for {, ] for [, and so on // Returns if ch is not opener // or closer boolean isBalanced(String s) { Answer: bool is Balanced(string s) { char ch, stch; int i =0; while(s[i]) // untill the end of the string { ch = s[i]; // pick the character

Page 78: CS301 Collection of  Old Papers

if( boolisOpener(ch); // if it is opener then push on the stack st.push(ch); else if( boolisCloser(ch) // if it is closer then pop the last char. from stack { stch = st.pop(); if( ch != MatchingChar(stch) // match the current char with stack char return false; // return false if not match } i++; // go to the next character } if(st.isempty()) // at the end stack should be empty return true; // if empty then return true else return false; // else return false; }

Page 79: CS301 Collection of  Old Papers

WWW.vujannat.ning.comhttp://vujannat.ning.com

Largest Online Community of VU Students

MIDTERM EXAMINATION SEMESTER SPRING 2004 CS301-DATA STRUCTURE

Total Marks:75 Duration: 60min

Instructions

Please read the following instructions carefully before attempting any question:

1. The duration of this examination is 60 Mins. 2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no

grade. 3. Unless stated otherwise, all questions carry a single mark. 4. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

5. You are allowed to use any development environment like Dev C++ etc.

Page 80: CS301 Collection of  Old Papers

Question No: 1 Marks: 5

Consider the following Mystery function. int Mystery(int num) { if (num > 4) { return 2 + Mystery(num - 5) + Mystery(num - 2); } return 1; } What is the value returned from the call Mystery(8)? Answer : 7 Question No: 2 Marks: 10

Write function circularcount that returns the number of nodes in a circularly-linked list like the one illustrated below.

int circularcount(Node* list) // pre: list is circular // post: return # nodes in list, list is unchanged { Answer int circularcount(Node* list) { if(list==NULL) { return 0; } else { Node *temp,*move; Temp=move=list; int count=1; move=move->next;

Page 81: CS301 Collection of  Old Papers

while(move!=temp) { count++; move=move->next; } } } Question No: 3 Marks: 15

Write the function Best that will take two linked lists as input for the creation of new linked list that consists or the larger of the two nodes from each input list. If one list runs out before the other, the resulting list consists entirely of info fields from the longer list after that point. For example if we had list A represented as list A -> 8 -> 6 -> 9 -> 13 -> 5 -> 8 / and listB as list B -> 10 -> 2 -> 19 / we should expect Best to return 10 -> 6 -> 19 -> 13 -> 5 -> 8 / were ‘/’ represents the NULL pointer. class Node { public: Node(const int item, Node* ptr) { info = item; next = ptr; } private: int info; Node* next; }; Node* best(Node* listA, Node* listB) // pre: listA and listB are each NULL-terminated, linked lists with NO // header nodes. Either or both may be empty. // post: returns pointer to a NULL-terminated, linked list with NO // header node. The Nth node of the new list contains a copy // of the larger info fields of the Nth node of listA and the Nth // of listB. If the Nth node of either of the input lists does // not exist, then the resulting list contains a copy of the node // from the other list. Lists pointed to by listA and listB are

Page 82: CS301 Collection of  Old Papers

// unchanged. { Answer: Node *best(Node *listA,Node *listB) { Node *temp=NULL; If(listA==NULL&& listB==NULL) //if both lists are empty then return NULL { return temp;

} else if (listA==NULL) //create temporary list place all node of listB in it and return its address { Node *templistB=listB; While(templistB!=NULL) { Temp=new Node(templistB->info,temp); templistB=templistB->next;

} return temp;

} else if (listB==NULL) //create temporary list place all node of listA in it and return its address { Node *templistA=listA; While(templistA!=NULL) { Temp=new Node(templistA->info,temp); templistA=templistA->next;

} return temp;

} else //if both lists are not empty { Node *templistA=listA; Node *templistB=listB; While(templistA!=NULL && templistB!=NULL) { if(templistA->info>templistB->info) { Temp=new Node(templistA->info,temp); templistA=templistA->next; templistB=templistB->next;

} else {

Temp=new Node(templistB->info,temp); templistA=templistA->next; templistB=templistB->next;

Page 83: CS301 Collection of  Old Papers

}

} if (templistA==NULL)

{ While(templistB!=NULL) { Temp=new Node(templistB->info,temp); templistB=templistB->next;

} return temp;

} else if (listB==NULL) {

While(templistA!=NULL) { Temp=new Node(templistA->info,temp); templistA=templistA->next;

} return temp;

} } Question No: 4 Marks: 5

What is the value of the postfix expression: 7 5 3 + * 5 2 - 8 9 * + + Answer:

Input op1 op2 value stack 7 7 5 5

7 3 3

5 7

+ 5 3 8 8 7

* 7 8 56 56 5 5

56 2 2

5 56

- 5 2 3 56

8 8 3 56

9 9 8 3 56

* 8 9 72 72 3 56

Page 84: CS301 Collection of  Old Papers

+ 3 72 75 75 56

+ 56 75 131 131 Result of Postfix Expression = 131 Question No: 5 Marks: 5

Write a postfix expression equivalent to 13 + 4 * ( 10 - 3 ). Note that this expression has the value 41. Answer: 13 4 10 3 - * +

Step No. Symbol Postfix Stack 1 13 13 2 + 13 + 3 4 13 4 + 4 * 13 4 + * 5 ( 13 4 + * 6 10 13 4 10 +*( 7 - 13 4 10 +*(- 8 3 13 4 10 3 +*(- 9 ) 13 4 10 3 - +* 10 13 4 10 3 - * +

Question No: 6 Marks: 15

Suppose that a Stack class is implemented and will be used to implement a Queue class. The only data members in the private section of the Queue class are an integer representing the number of elements in the queue and a stack for storing queue elements. private: Stack<Etype> myStack; int mySize; The member function for Enqueue is shown below (recall that both stack and queue classes are tem- plated). Queue<Etype>::Enqueue( const Etype & X ) // postcondition: X added to rear of queue { myStack.push(X); mySize++; } Describe briefly how to implement the function Dequeue that removes the first element from the queue. You do NOT need to write code (although you can), but do need to describe how to dequeue an element when elements are stored and enqueued as described above. Answer:

1- Create temporary stack 2- Pop elements from mystack and push in temporary stack until mystack is empty.

Page 85: CS301 Collection of  Old Papers

3- Pop the value from temporary stack. This is the required dequeue value. 4- Now pop all elements from temporary stack and push them again in mystack.

Question No: 7 Marks: 20

The tree below is a binary search tree (BST).

a) What nodes of the tree above are leaves? b) What is the postorder traversal of the tree above? c) Add the following strings, in order, to the tree. Draw new nodes attached to the tree above. Add butter, kidney, soy, and red in that order. d) What are the minimum and maximum heights of a binary search tree storing 2048 = 211

different strings? Answer:

a) black, garbanzo,pinto b) black, garbanzo, chickpea, pinto, navy, lima c) lima / \ chickpea navy / \ \ black garbanzo pinto \ \ \ butter kidney soy / red d) Minimum Height d= log2(n+1)-1 = log2(2048+1)-1 = 10 Maximum Height = 2047

Page 86: CS301 Collection of  Old Papers
Page 87: CS301 Collection of  Old Papers

www.vujannat.ning.com

A stack is a special kind of list in which all insertions and deletions take place at one end A list is a sequence of one or more data items Lists can be implemented by using arrays or linked lists

Four statements about lists and stacks are given below. Three of them are correct. Which one is incorrect?

Question No. 1 Marks : 2

**WARNING: Please note that Virtual University takes serious note of unfair means.

Anyone found involved in cheating will get an `F` grade in this course.

You are allowed to use the Dev-C++ compiler to write and test your code. If you do so please remember to copy and paste your code into the examination solution area. (Do NOT share your code; your colleague could get higher marks than you!!)

d. All coding questions should be answered using the C ++ syntax. c. Write all steps, missing steps may lead to deduction of marks.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

2. Do not ask any questions about the contents of this examination from anyone.

1. Attempt all questions. Marks are written adjacent to each question.

Time Allowed: 90 Minutes Mid Term Examination – Spring 2006 CS301 Data Structures

Page 88: CS301 Collection of  Old Papers

MyQueue q; MyStack s; q = new MyQueue(); s = new MyStack(); s.push(5);

What is the output of the following tester program for MyQueue and MyStack? (10)

Question No. 5 Marks : 10

s height. Tree2' must also be greater

than Tree1's size, then the height of Tree2's size is greater than Tree1 If

A search tree is a special type of tree where all values (i.e. keys) are ordered

The order of a tree indicates a maximum number of childen allowed at each node of the tree

Trees are recursively defined multi-dimensional data structures

Four statements about trees are given below. Three of them are correct. Which one is INCORRECT?

Question No. 4 Marks : 2

To remove an element from the middle of the list We cannot remove element from an array list To remove an element from the start of the list To remove an element from the end of the list

In an array list the worst case of removing an element is Question No. 3 Marks : 2

None of these All Leaf node Root Node

The node with no successors are called _____ Question No. 2 Marks : 2

Stacks are easier to implement than lists

Page 89: CS301 Collection of  Old Papers

13 12 11 10 9 8 7 6 5 4 3

2 1

postfix Stack Symbol Step No Answer:

Convert the infix expression ((A+b)*D ^ (E- F) ) to postfix. Show the trace of the algorithm. (10)

Question No. 7 Marks : 10

Draw a Binary Search Tree (BST) for following Integers given: 37, 30, 15, 45, 32, 91, 40,18 (10)

Question No. 6 Marks : 10

Answer :

Cout<<s.pop()); q.enqueue(s.pop()); q.enqueue(5); q.enqueue(6); cout<<q.dequeue(); s.push(q.dequeue()); cout<<s.pop(); cout<<s.pop();

s.push(6); s.push(7);

Page 90: CS301 Collection of  Old Papers

. This method will take two arguments and both will be of type string.

replace(string, string)You are required to write code for the method //--------------------------------------------------------------------------------- }; int mySize; // # nodes in linked list Node * myTail; // last node in list, header if list is empty Node * myHead; // header node private: void replace(string, string ); void removeNode(string ); void printList() ; void add(Node *) ; int size() const; ~LinkedList(); LinkedList(); public: { class LinkedList //--------------------------------------------------------------------------------- }; next(nptr) { } : store(word), Node (const string& word, Node * nptr) Node * next; string store; { struct Node //---------------------------------------------------------------------------------

node will consist of the string “I” and second node will consist of string “am” third will consist of “taking” ans so on.

st

Here is a code of link list which saves the sentence in the link list such that each node consist of part of sentence (string) e.g. “I am taking examination” then there will be four nodes and 1

Question No. 8 Marks : 10 Final Postfix: Note : ^ Notation used for exponentiations

16 15 14

Page 91: CS301 Collection of  Old Papers

Bidirectional. Self-referential. Recursive. Redundant.

"linked list" always contains elements that can be described as? Question No. 9 Marks : 2 replace(“tomorrow”, “yesterday”);

We need to replace the string “tomorrow” with the string “yesterday” so we call the method like this

Suppose the link list consists of sentence “I have taken the examination tomorrow” Here is an example

Incase if method failed to find the string it will display the message “String not found”

First argument will be the string which will be searched through the link list to replace and second argument will be the string which it will be replace in the link list.

Page 92: CS301 Collection of  Old Papers

WWW.vujannat.ning.com

http://vujannat.ning.com Largest Online Community of VU Students

MIDTERM EXAMINATION

SPRING 2007

CS301 - DATA STRUCTURES (Session - 1 )

Marks: 50

Time: 90min

Q1. (10) Describe the tree in data structure also describe Binary tree with example? Q2.(5) Consider the following infix expression. 3*2^5-1 Converts the above expression into postfix and show the step by step process of conversion. Q3.(2) Queue operations are very similar to stack operations. Which of the following definitions is not suitable for both applications? 1) Is_empty – check to see if the application is empty. 2) Is_full( ) – check to see if the application is full. 3) Delete( )- remove the most recently inserted item from the application. 4) Clear( ) – clear the data structure. Q4.(2) The following are statements related to queues.

(i) The last item to be added to a queue is the first item to be removed (ii) A queue is a structure in which both ends are not used (iii) The last element hasn’t to wait until all elements preceding it on the queue are removed (iv)A queue is said to be a last-in-first-out list or LIFO data structure

Which of the above is/are related to normal queues? i) None of above ii) 2 and 4 only iii) 1,2 and 4only iv) 3 and 2 only.

Q5.(5) Consider the following infix expression: (( A+B) * C – (D-E)) ^(F + G) Converts the above expression into prefix and show the step by step process of conversion. Q6. (2) Commomly simulation models are

1) a & b 2) (c)Timeless simulation 3) (b) Event based simulation 4) (a)time –bases simulation

Page 93: CS301 Collection of  Old Papers

Q7.(2) Which of the following is a stack application in the real world? i) Printing jobs from the spooler directory ii) Walk in criteria, when one gets into the food line and picks up a tray iii) Walk in criteria, when one gets into the food line

iv) Creating a directory structure in Dos Q8. (2) Consider the following tree.

J

B

F G I

L

C D

A

H

K

E

M

The following are (iv) statements about the above tree.

(i) Depth of the above tree is equal to 4. (ii) Height of the above tree is equal to 3. (iii) There is only one sibling belonging to Node B. (iv) The proper ancestors of I are L and M only.

Which one of the following is correct in respect of the above statements?

1) ii. Only 2) iii.only 3) I,ii,and iii only 4) I ;and iiii only

Q9. (10)

Describes the list implementation with following methods? Add method Find method Remove method

Q10. 6) Consider the linked list given bellow.

2 10 12 13

31 31 29 25 25 20 20 Transformed the above linked list into a binary search tree.

Q.11 (2) Consider the following stack with the indicated initials status and series of stack operations.

Page 94: CS301 Collection of  Old Papers

Top=3

(i) Pop( ); (ii) Pop( ); (iii) Push(t); (iv) Push(u) (v) Push(v); (vi) Pop( ); (vii) Pop( ); (viii) Pop( );

If the above series of operation is performed, what is final position of top and contents of the top respectively?

i) 2.u (ii)1,q (iii) 1.t (iv) 1,v Q12. (2)

Consider the following (iv) statements.

(i) A binary tree can contain at least 2L Nodes at level L. (ii) A complete binary tree of depth d is a binary tree that contains 2L Nodes at each level

L between 0 and d, both inclusive. (iii) The total number of nodes (Tn ) in a complete binary tree of depth d is 2 d+1 - 1 . (iv) The height of the complete binary tree can be written as h = log 2 (Tn+1)-1 where Tn

is Total number of Nodes. Which one of the following is correct in respect of the above statements regarding the Binary trees?

1) ii, iii and iv only 2) ii and iii only 3) I, ii and iii only 4) Iii only

Page 95: CS301 Collection of  Old Papers

WWW.vujannat.ning.comhttp://vujannat.ning.com

Largest Online Community of VU Students MIDTERM EXAMINATION

SPRING 2007

CS301 - DATA STRUCTURES (Session - 4 )

Marks: 50

Time: 90min

StudentID/LoginID: ______________________________

Student Name: ______________________________

Center Name/Code: ______________________________

Exam Date: Monday, May 14, 2007

Please read the following instructions carefully before attempting any question:

1. This examination is closed book, closed notes, closed neighbors; anyone found cheating will get no grade.

2. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

3. Most, but not all, of the examination consists of multiple-choice questions. Choose only one choice as your answer.

a. If you believe that two (or more) of the choices are the correct ones for a particular question, choose the best one.

b. On the other hand, if you believe that all of the choices provided for a particular question are the wrong ones, select the one that appears to you as being the least wrong.

(Do NOT share your code; your colleague could get higher marks than you!!)

**WARNING: Please note that Virtual University takes serious note of unfair means. Anyone found involved in cheating will get an `F` grade in this course

Page 96: CS301 Collection of  Old Papers

For Teacher's use only Question 1 2 3 4 5 6 7 8 9 10 Total

Marks Question 11 12

Marks Question No: 1 ( Marks: 2 ) - Please choose one The order of precedence in multiplication,. addition & subtraction is ►

highest to highest

highest to lowest

lowest to lowest

Lowest to highest

Question No: 2 ( Marks: 2 ) - Please choose one the preorder method in B tree is called for the ►

right node

left node

both nodes

none of the above

Question No: 3 ( Marks: 2 ) - Please choose one Consider the following tree and four (04) statements.

(i) The above tree is a binary search tree. (ii) The above tree is a AVL tree. (iii) The above tree is a Heap. (iv) The above tree is a Binary tree. ►

(i) and (iii) only

Page 97: CS301 Collection of  Old Papers

(i) only

(i) and (ii) only

(i) and (iv) only

Question No: 4 ( Marks: 2 ) - Please choose one Which of the following statement is correct in relation to AVL trees? ►

If three nodes lie in a straight line, a double rotation is needed to restore the balance.

If three nodes lie in a straight line, a single rotation is needed to restore the balance.

If three nodes lie in a dog-leg pattern (that is, there is a bend in the path), you need to perform a single rotation to restore the balance.

If three nodes lie in a dog-leg pattern (that is, there is a bend in the path), you need to perform a single rotation twice to restore the balance.

Question No: 5 ( Marks: 2 ) - Please choose one Which of the following is a more complete recursive definition(s) for a tree? ►

A tree consists of left and right sub-trees.

A tree consists of left and right sub-trees and value of the right child node is higher with respect the root and less than left child.

(i)An Empty structure is an empty tree. (ii)If t1,t2,t3,……..tk are disjoint trees, then the structure whose root has as its children the roots of t1,t2…….tk is also a tree. (iii)Only structures generated by rules (i) and (ii) are trees.

A tree consists of left and right sub-trees and value of the right child node is smaller with respect the root and higher than left child.

Question No: 6 ( Marks: 2 ) - Please choose one A tree with such a property that items in the left sub-tree are smaller than the root and items in the right sub-tree are larger than the root is called a ►

AVL tree

BST

Graph

► Circular queue

Page 98: CS301 Collection of  Old Papers

Question No: 7 ( Marks: 2 ) - Please choose one

If one fixed the violation property of the above AVL tree, what would be the resulting tree? ►

a

b

c

d

Question No: 8 ( Marks: 6 ) Consider the following expression tree representation. Give the step by step inorder traversing

Question No: 9 ( Marks: 5 ) Convert following infix expression to postfix and show the conversion process. A ↑ B * C – D + E/F

Page 99: CS301 Collection of  Old Papers

Question No: 10 ( Marks: 5 ) void order(TreeNode<int>* treeNode) { if( treeNode != NULL ) { order(treeNode->getLeft()); cout << *(treeNode->getInfo())<<" "; order(treeNode->getRight()); } } Describes the code with respect to traversing. Question No: 11 ( Marks: 10 ) Briefly describes the (ADT) with examples? Question No: 12 ( Marks: 10 ) What is cost of a search & describe it with example in tree data structure?

Page 100: CS301 Collection of  Old Papers

WWW.vujannat.ning.comhttp://vujannat.ning.com

Largest Online Community of VU Students Virtual University Government of Pakistan

Summer Session Examination 2003

Data Structure (CS301)

StudentID/LoginID Name PVC Name/Code Date August 16, 2003

Instructions

Please read the following instructions carefully before attempting any question:

1. The duration of this examination is 60 Mins.

2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no grade.

3. Unless stated otherwise, all questions carry a single mark.

4. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

Page 101: CS301 Collection of  Old Papers

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

5. Most, but not all, of the examination consists of multiple-choice questions. Choose only one choice as your answer.

a. If you believe that two (or more) of the choices are the correct ones for a particular question, choose the best one.

b. On the other hand, if you believe that all of the choices provided for a particular question are the wrong ones, select the one that appears to you as being the least wrong.

7. You are allowed to use any development environment like Dev C++ etc.

CS301-Data Structure

Time allowed: 60 minutes Max Marks: 51

1. Can two classes contain member functions with the same name? [2 pts]

A. No. B. Yes, but only if the two classes have the same name. C. Yes, but only if the main program does not declare both kinds. D. Yes, this is always allowed.

2. What is the best C++ statement to use when a program must choose between several alternatives that are controlled by the value of a single variable? [2 pts]

A. do-while statement B. for statement C. if-else statement

Page 102: CS301 Collection of  Old Papers

D. switch statement E. while statement

3. Consider the following statements: [2 pts]

int *p; int i; int k; i = 42; k = i; p = &i;

After these statements, which of the following statements will change the value of i to 75?

A. k = 75; B. *k = 75; C. p = 75; D. *p = 75; E. Two or more of the answers will change i to 75.

4. What is the value of the postfix expression 6 3 2 4 + - * [5 pts]

A. Something between -15 and -100 B. Something between -5 and -15 C. Something between 5 and -5 D. Something between 5 and 15 E. Something between 15 and 100

5. Here is an infix expression: 4+3*(6*3-12). Suppose that we are using the usual stack algorithm to convert the expression from infix to postfix notation. What is the maximum number of symbols that will appear on the stack AT ONE TIME during the conversion of this expression? [5 pts]

A. 1 B. 2 C. 3 D. 4 E. 5

6. I have implemented the queue with a circular array, keeping track of first, last, and count (the number of items in the array). Suppose first is zero, and

Page 103: CS301 Collection of  Old Papers

last is CAPACITY-1. What can you tell me about count? [5 pts]

A. count must be zero. B. count must be CAPACITY. C. count could be zero or CAPACITY, but no other values could occur. D. None of the above.

7. Consider the following function: [5 pts]

void test_b(int n) {

if (n>0) test_b(n-2);

cout << n << " "; }

What is printed by the call test_b(4)?

A. 0 2 4 B. 0 2 C. 2 4 D. 4 2 E. 4 2 0

8. A partial declaration for a singly-linked integer list class is as follows: [10 pts] class Node { public:

int data; Node* next; Node(int d, Node *n) {

data = d; next = n; } void setData( int data ) { this->data = data;} int getData() { return data; } void setNext( Node* ptr ){ this->next = ptr; } Node* getNext() { return next; }

}; class intList

Page 104: CS301 Collection of  Old Papers

{ public:

//... // return the product of the data values in nodes of the // list. int product(); // return the number of times the given "value" occurs as // data in the int occurs( int value ); // ....

private: Node* head; // points to the first Node in the

list Node* current;// a cursor pointer

}; A. Write the code for the member function product which returns the product of the data values stored in the nodes of the list. B. Provide the code for the member function occurs which counts the number of times the given value occurs in the list. For example, if the 6 nodes in the list contain the number 42, occurs will return 6. 9. I am going to execute this code with THREE pushes and ONE pop: [5 pts]

stack<int> s; s.push(1); s.push(2); s.push(3); cout << s.pop( );

Suppose that s is represented by a linked list. Draw the state of the private member variables of s after the above code:

_______ head_ptr | |

|_______|

Page 105: CS301 Collection of  Old Papers

10. Write a recursive function to meet the following specification. [10 pts]

void flip(binary_tree_node* root) // ’root’ is the root pointer of a non-empty binary

tree. // The function flips the tree to create a mirror

image of // its original value. // Example original tree: Example new tree: // // 1 1 // / \ / \ // 2 3 3 2 // / \ / \ // 4 5 5 4

Page 106: CS301 Collection of  Old Papers

WWW.vujannat.ning.comhttp://vujannat.ning.com

Largest Online Community of VU Students Virtual University Government of Pakistan

Summer Session Examination 2003

Data Structure (CS301)

StudentID/LoginID Name PVC Name/Code Date August 16, 2003

Instructions

Please read the following instructions carefully before attempting any question:

1. The duration of this examination is 60 Mins.

2. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no grade.

3. Unless stated otherwise, all questions carry a single mark.

4. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

5. Most, but not all, of the examination consists of multiple-choice questions. Choose only one choice as your answer.

a. If you believe that two (or more) of the choices are the correct ones for a particular question, choose the best one.

Page 107: CS301 Collection of  Old Papers

b. On the other hand, if you believe that all of the choices provided for a particular question are the wrong ones, select the one that appears to you as being the least wrong.

7. You are allowed to use any development environment like Dev C++ etc.

CS301-Data Structure

Time allowed: 60 minutes Max Marks: 51 1. Is it possible for a member function of a class to activate another member function of the same class? [2 pts]

A. No. B. Yes, but only public member functions. C. Yes, but only private member functions. D. Yes, both public and private member functions can be activated within another member function.

2. Consider this class definition: [2 pts]

class quiz { public:

quiz( ); int f( ); int g( ) const;

private: double score;

}; Which functions can carry out an assignment score=1.0; to the private ember variable score?

A. Both f and g can carry out the assignment. B. f can carry out the assignment, but not g. C. g can carry out the assignment, but not f. D. Neither f nor g can carry out the assignment.

3. Here is a small function definition: [2 pts]

void f(int i, int &k) {

i = 1; k = 2;

} Suppose that a main program has two integer variables x and y, which are given the value 0. Then the main program calls f(x,y);What are the values of x and y after the function f finishes?

Page 108: CS301 Collection of  Old Papers

A. Both x and y are still 0. B. x is now 1, but y is still 0. C. x is still 0, but y is now 2. D. x is now 1, and y is now 2.

4. Consider the following pseudocode: [2 pts]

declare a stack of characters while ( there are more characters in the word to read ) {

read a character push the character on the stack

} while ( the stack is not empty ) {

write the stack’s top character to the screen pop a character off the stack

} What is written to the screen for the input “carpets”?

A. serc B. carpets C. steprac D. ccaarrppeettss

5. Suppose we have a circular array implementation of the queue class, with ten items in the queue stored at data[2] through data[11]. The CAPACITY is 42, i.e., the array has been declared to be of size 42. Where does the push member function place the new entry in the array? [2 pts]

A. data[1] B. data[2] C. data[11] D. data[12]

6. I have implemented the queue with a circular array. If data is a circular array of CAPACITY elements, and last is an index into that array, what is the formula for the index after last? [2 pts]

A. (last % 1) + CAPACITY B. last % (1 + CAPACITY) C. (last + 1) % CAPACITY D. last + (1 % CAPACITY)

7. Consider the following function: [5 pts]

void test_a(int n) {

cout << n << " "; if (n>0)

test_a(n-2); }

Page 109: CS301 Collection of  Old Papers

What is printed by the call test_a(4)?

A. 0 2 4 B. 0 2 C. 2 4 D. 4 2 E. 4 2 0

8. A partial declaration for a singly-linked integer list class is as follows: [10 pts] class Node {

public: int data; Node* next; Node(int d, Node *n) {

data = d; next = n; } void setData( int data ) { this->data = data;} int getData() { return data; } void setNext( Node* ptr ){ this->next = ptr; } Node* getNext() { return next; }

}; class intList {

public: // ... // Insert a new node at the tail of the list with //value ’data’ stored new node. void tailInsert( int data ); // return the sum of the data values in nodes of the //list. int sum(); // ....

private: Node* head; // points to the first Node in the list Node* current;// a cursor pointer

}; A. Write the code for the member function tailInsert which inserts a new node at the end (tail) of the list. The new node stores the integer ’data’. Your code must take care of the case when the list is empty. B. Write the code for the member function sum which returns the sum of the data values stored in the nodes of the list.

Page 110: CS301 Collection of  Old Papers

9. Consider the usual algorithm to convert an infix expression to a postfix expression. Suppose that you have read 10 input characters during a conversion and that the stack now contains these symbols: [10 pts]

| | | + |

| ( | bottom |_*_|

Now, suppose that you read and process the 11th symbol of the input. Draw the stack for the case where the 11th symbol is: A. A number: B. A left parenthesis: C. A right parenthesis: D. A minus sign: E. A division sign:

10. Here is a small binary tree: [5 pts]

14

/ \ 2 11

/ \ / \ 1 3 10 30

/ / 7 40

A. What are all the leaves? (1pts) B. What are the ancestors of the node 10? (2pts) C. What are the descendants of the node 10? (2pts)

11. Here is a small binary tree: [9 pts] 14

/ \ 2 11

/ \ / \ 1 3 10 30 / / 7 40

Write the order of the nodes visited in:

A. An in-order traversal: B. A pre-order traversal: C. A post-order traversal:

Page 111: CS301 Collection of  Old Papers

http://vujannat.ning.com BEST SITE TO HELP STUDENTS

MIDTERM EXAMINATION

SUMMER 2007

CS301 - DATA STRUCTURES (Session - 1 )

Marks: 50

Time: 120min

StudentID/LoginID: ______________________________

Student Name: ______________________________

Center Name/Code: ______________________________

Exam Date: Wednesday, August 15, 2007

Please read the following instructions carefully before attempting any question:

1. Mobile Phones are strictly prohibited in the examination center.

2. Dev C++ or any other software is not allowed.

3. The duration of this examination is 90 Mins.

4. This examination is closed book, closed notes, closed neighbors; any one found cheating will get no grade.

5. Unless stated otherwise, all questions carry a single mark.

6. Do not ask any questions about the contents of this examination from anyone.

a. If you think that there is something wrong with any of the questions, attempt it to the best of your understanding.

b. If you believe that some essential piece of information is missing, make an appropriate assumption and use it to solve the problem.

7. Most, but not all, of the examination consists of multiple-choice questions. Choose only one choice as your answer.

a. If you believe that two (or more) of the choices are the correct ones for a particular question, choose the best one.

On the other hand, if you believe that all of the choices provided for a particular question are the wrong ones, select the one that appears to you as being the least wrong.

For Teacher's use only Question 1 2 3 4 5 6 7 8 9 Total

Marks

Question No: 1 ( Marks: 2 ) - Please choose one When we say the order of a tree is M, we mean that every non-leaf node must have M

Page 112: CS301 Collection of  Old Papers

subtrees. ►

True

False

Question No: 2 ( Marks: 2 ) - Please choose one The time complexity of an ordered list of inserting/deleting a data item to/from the list is O(length_of_list*length_of_list) ►

True

False

Question No: 3 ( Marks: 2 ) - Please choose one An unbalanced tree is one whose root has many more left descendents than right descendents ►

True

False

Question No: 4 ( Marks: 2 ) - Please choose one Stack and queue data structures are needed to convert the infix notations to post fix notations. ►

True

False

Question No: 5 ( Marks: 2 ) - Please choose one A sequential search of the elements is faster than the binary search of an ordered set of elements in an array. ►

True

False

Question No: 6 ( Marks: 10 ) Convert the infix expression (A - B) * C + D to postfix. Show the trace of the algorithm, i.e., the stack, the infix expression and postfix expression.

Question No: 7 ( Marks: 10 ) Given two sorted lists, L1 and L2, Write the following routine to compute L1 ∩ L2

using only the basic list operations.

Page 113: CS301 Collection of  Old Papers

List intersection(List list1, List list2){ // Write the complete code to compute L1 ∩ L2 }

here.

Question No: 8 ( Marks: 10 ) Consider a binary search tree (BST) that is initially empty. Draw the tree that will result if the following numbers are inserted in the order given: 35, 28, 13, 43, 30, 89, 38, 16, 12, 40

Question No: 9 ( Marks: 10 ) Consider the following binary tree: (a) Starting from the root node, perform an In-order traversal of the binary tree below and write the letters in the nodes that will result during the visitations. (b) Write the nodes if a Pre-order traversal is performed starting with node O.

O

M H

N S

F I

A