Professional Documents
Culture Documents
#include <iostream>
void fun(int x) {
x = 30;
}
int main() {
int y = 20;
fun(y);
std::cout << y;
return 0;
}
A1: B
(2pt) Q2: This is a piece of code from your peer’s HW0-Linked List. Point out which 2 lines are wrong and
briefly explain the reason.
struct _listnode {
int data; // line 1
_listnode *next; // line 2
};
class Linkedlist {
private:
_listnode *header; // line 3
int length; // line 4
public:
… …
}
Linkedlist::Linkedlist() {
header = _listnode; // line 5
header->data = -1; // line 6
header->next = nullptr; // line 7
length = 0;
}
int main(void) {
… …
Linkelist ll;
_listnode *first = ll.header; // line 8
… …
}
A2:
line 5: header=_listnode;=>he/she doesn’t allocate memory with new (1’)
line 8: _listnode *first = ll.header; => header is private (1’)
(1pt) Q3: These are two versions of your peers’HW0-Stack. Tick a √ for your answer.
A B
#include … #include …
A3:
A B
(2pt) Q4: Suppose x is a linked-list node and not the last node on the list. What is the effect of the following
code fragment?
x.next = x.next.next
(2pt) Q5: Write a function of swapping the value of x and y, the space is for you to implement.
(3pt) Q6: Try to swap the value of two variable x and y by only using XOR. (Hint: consider the results of a
XOR a and a XOR 0.)
A6: x = x XOR y;
y = x XOR y;
x = x XOR y;
(2pt) Q7: Suppose that x is a linked list Node, write two clauses of code to insert node t immediately after
node x.
A7: t.next = x.next;
x.next = t;
(2pt) Q6: We can use an array to implement a linked list as an alternative method. A continuous part of array
A[j, j+1] represents the attributes key and next of a node. Look the example below and draw the linked
list it represents. We know that L.head = 2.
index 0 1 2 3 4 5 6 7 8 9 10 11
value 3 10 1 6 4 0 5 4 / / 2 /
A6: 1→5→4→3→2
(Bonus 2pt) Q9: Professor Yu talked about how many 1 in a number’s decimal form. He gave you a subtle
method and asked you to understand it after class. Now tell us how it works.
while (a) {
count++;
a &= a-1;
}
A9: If the student mentions eliminating the last 1 each time, then he/she gets the full points.
e.g. odd: 11101 & 11100 = 11100; even: 11100 & 11011 = 11000;