codekofi
← All problems

Problem 97

Easy

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1struct Node {
2 int val;
3 Node* next;
4};
5
6Node* build(const vector<int>& values) {
7
8 Node stub{0, nullptr};
9 Node* tail = &stub;
10
11 for (int v : values) {
12 tail->next = new Node{v, nullptr};
13 tail = tail->next;
14 }
15
16 return stub.next;
17}
18
19bool loops(Node* head) {
20
21 Node* slow = head;
22 Node* fast = head;
23
24 while (fast && fast->next) {
25
26 slow = slow->next;
27 fast = fast->next->next;
28
29 if (slow == fast) {
30 return true;
31 }
32 }
33
34 return false;
35}
36
37bool solution(const vector<int>& values, int joinAt) {
38
39 Node* head = build(values);
40
41 if (joinAt >= 0 && head) {
42
43 Node* target = head;
44
45 for (int i = 0; i < joinAt; i++) {
46 target = target->next;
47 }
48
49 Node* tail = head;
50
51 while (tail->next) {
52 tail = tail->next;
53 }
54
55 tail->next = target;
56 }
57
58 return loops(head);
59}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.