-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCount_nodes_in_CLL.cpp
86 lines (74 loc) · 1.24 KB
/
Count_nodes_in_CLL.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *next;
};
void printList(Node *head)
{
Node *t = head;
if (head == NULL)
return;
do
{
cout << t->data << ' ';
t = t->next;
} while (t != head);
}
Node *_last = NULL;
Node *insertEnd(Node *head, int data)
{
Node *node = new Node();
node->data = data;
if (head != NULL)
{
_last->next = node;
}
else
head = node;
node->next = head;
_last = node;
return head;
}
/*
* struct Node {
* int data;
* Node *next;
* };
*
* The above structure defines the linked list node.
*/
int countNodes(Node *head)
{
// Write your code here
if (head == nullptr)
return 0;
if (head->next == head)
return 1;
Node *temp = head->next;
int nodes = 2;
while (temp->next != head && temp) {
nodes++;
temp = temp->next;
}
return nodes;
}
int main()
{
int t;
cin >> t;
while (t--)
{
Node *head = NULL;
int n, data;
cin >> n;
while (n--)
{
cin >> data;
head = insertEnd(head, data);
}
cout << countNodes(head) << endl;
}
return 0;
}