You are on page 1of 2

----

Q3
----
char *strncpy(char *s1, const char *s2, int n) {
char *p = s1;
const char *p2 = s2;

for (int i = 0; i < n - 1; i++) {


if (*p2 != '\0') {
*p = *p2;
++p2;
++p;
if ((i + 1) == (n - 1) && *p2 == '\0') {
*p = *p2;
}
} else {
*p = *p2;
break;
}
}
if (*p2 != '\0') {
*p = '\0';
}
return s1;
}

----
Q6
----
(a) The list destructor is executed when the delete operator is used or when the list class goes out of
scope.

(b) list::~list() {
while (L != nullptr) {
node *temp = L;
L = L->next;
delete temp;
}
}

(c) The node destructor is executed when the delete operator is used or when the node object goes out
of scope.
(d) The default node destructor is sufficient because there aren't any variables within the node class that
require special actions. All that is needed is to delete the memory used by the node object.

(e) void list::magic6A(int key) {


node *newNode = new node;
newNode->key = key;

node *prev = L;
node *current = L->next;

while (current != nullptr && current->key < key) {


prev = current;
current = current->next;
}

prev->next = newNode;
newNode->next = current;
}

(f) After magic6b is called, L = {45, 22, 18, 10}

----
Q8
----
template <typename ContainerA, typename ContainerB>
void copy(ContainerA& A, const ContainerB& B) {
A.resize(B.size());

auto aIt = A.begin();


auto bIt = B.begin();

while (bIt != B.end()) {


*aIt = *bIt;
++aIt;
++bIt;
}
}

You might also like