forked from skylarbpayne/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlength_circ_list.cpp
More file actions
65 lines (57 loc) · 1022 Bytes
/
length_circ_list.cpp
File metadata and controls
65 lines (57 loc) · 1022 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Author: Skylar Payne
* Date: December 24, 2014
* Find the length of a circular linked list
**/
#include <iostream>
#include <time.h>
#include <assert.h>
class Node {
public:
int value;
Node* next;
Node(int v, Node* n = nullptr) : value(v), next(n) { }
};
unsigned int length(Node* node) {
if(node == nullptr)
return 0;
unsigned int len = 1;
Node* n = node->next;
while(n != node) {
n = n->next;
++len;
}
return len;
}
Node* insert_node(Node* s, int v) {
if(s == nullptr) {
s = new Node(v);
s->next = s;
return s;
}
s->next = new Node(v, s->next);
return s;
}
void destroy_list(Node* s) {
if(s == nullptr)
return;
Node* n = s->next;
while(n != s) {
Node* t = n;
n = n->next;
delete t;
}
delete s;
}
int main(int argc, char** argv) {
srand(time(NULL));
unsigned int len = rand() % 100;
Node* l = nullptr;
for(int i = 0; i < len; ++i) {
l = insert_node(l, 0);
}
assert(len == length(l));
std::cout << "Test passed" << std::endl;
destroy_list(l);
return 0;
}