Uploaded by Mirna Laffi

CSCI378 - Sample Test- Solution

advertisement
CSCI378 – Data Structures and Algorithms
Sample Midterm Exam - Solution
Question 1 [60 points]
Write a concatenate( ) method that takes two linked lists, list1 and list2, and appends list2 onto the end
of list1.
For example, if the lists were originally:
List1
head
3

6

7

List2
head
9

5

3
|||
2
|||
And
Then List1 becomes after concatenation:
head
3

6

7

2

9

5

3
|||
Solution 1 (Better)
public static void concatenate(LinkedList list1, LinkedList list2){
Node curr2 = list2.getHead();
// 10 pts
while (curr2 != null) { // move to the tail of list2 // 20 pts
list1.addTail(curr2.getData()); // 20 pts
curr2 = curr2.getNext(); // 10 pts
}
} // end concatenate
Solution 2
public static void concatenate(LinkedList list1, LinkedList list2){
Node curr1 = list1.getHead(); // 4 pts
int pos = 1;
// 3 pts
while (curr1 != null) { // move to the end of list1
curr1 = curr1.getNext(); // 5 pts
pos++; // 3 pts
}
pos++; // to insert at the end of list1 // 3 pts
Node curr2 = list2.getHead(); // 4 pts
while (curr2 != null) { // move to the end of list2
list1.insert(curr2.getData(), pos);
// 10 pts
curr2 = curr2.getNext(); // 5 pts
pos++;
// 3 pts
}
} // end concatenate
Page 1 of 2
// 10 pts
// 10 pts
CSCI378 – Data Structures and Algorithms
Sample Midterm Exam - Solution
Question 2 [25 pts]
a) Given the below linked list, what will be the content of the linked list after the execution of the
following code? [20 pts]
head
5

3

7

12

10
|||
Node y = head.next.next;
Node temp = head;
head = y.next;
head.next.next = temp;
temp = head.next;
Node n = new Node(new NodeData(8));
head.next = n;
head = temp;
y.data.value = 9;
Solution
head -> 10 -> 5 -> 3 -> 9 -> 12 -> 8 -> |||
b) What is the output of the following code? [20 pts]
LinkedList list = new LinkedList();
list.addHead(new NodeData(5));
list.addTail(new NodeData(4));
list.addHead(new NodeData(3));
list.addTail(new NodeData(2));
list.insert(new NodeData(1),2);
list.print();
Solution
head -> 3 -> 1 -> 5 -> 4 -> 2 -> |||
Page 2 of 2
Download