Вы находитесь на странице: 1из 3

CS101 Quiz 1-1 Answer

name: ID number: score:

(1pt) Q1: Read the code below:

#include <iostream>

void fun(int x) {
x = 30;
}

int main() {
int y = 20;
fun(y);
std::cout << y;
return 0;
}

The output is:


A: 30
B: 20
C: Runtime Error
D: None of above

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 …

class Stack {…} int main (void) {


char data[1000]
Stack::Stack () {…} if (…){…} else {…}
Stack::push(int value) {…} for(…){…}
Stack::isEmpty(){…} if (…) {printf(“Match”);}
else {printf(“Not match”);}
int main(void) {…} }

A3:
A B

Which one do you prefer?

Which one do you think TAs prefer?

Which one is better for your programming habit?

A(0’) A(0.5’) A(0.5’)

(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

A4: Deletes from the list the node immediately following x.

(2pt) Q5: Write a function of swapping the value of x and y, the space is for you to implement.

void Swap(int *x, int *y) {


int temp = *x;
*x = *y;
*y = temp;
} (1’ )
int main(void) {
int x = 3;
int y = 4;
Swap(&x, &y); (1’)
return 0;
}

(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;