-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathD61_Rotate a Linked List.cpp
More file actions
46 lines (42 loc) · 1.05 KB
/
D61_Rotate a Linked List.cpp
File metadata and controls
46 lines (42 loc) · 1.05 KB
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
// Given the head of a singly linked list, your task is to left rotate the linked list k times.
// Examples:
// Input: head = 10 -> 20 -> 30 -> 40 -> 50, k = 4
// Output: 50 -> 10 -> 20 -> 30 -> 40
// Explanation:
// Rotate 1: 20 -> 30 -> 40 -> 50 -> 10
// Rotate 2: 30 -> 40 -> 50 -> 10 -> 20
// Rotate 3: 40 -> 50 -> 10 -> 20 -> 30
// Rotate 4: 50 -> 10 -> 20 -> 30 -> 40
// Input: head = 10 -> 20 -> 30 -> 40 , k = 6
// Output: 30 -> 40 -> 10 -> 20
class Solution
{
public:
Node *rotate(Node *head, int k)
{
int n = 0;
Node *temp = head;
while (temp)
{
temp = temp->next;
n++;
}
k = k % n;
if (!(k) || n == 1)
return head;
temp = head;
while (--k)
{
temp = temp->next;
}
Node *nh = temp->next;
temp->next = NULL;
temp = nh;
while (temp->next)
{
temp = temp->next;
}
temp->next = head;
return nh;
}
};