-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate-list.cpp
74 lines (57 loc) · 1.36 KB
/
rotate-list.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
#include <iostream>
using namespace std;
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode *rotateRight(ListNode *head, int k) {
if (!head) return head;
else if(!head->next) return head;
ListNode *first = head;
ListNode *second = head;
while (k > 0) {
second = second->next;
k--;
if (second == nullptr) {
second = head;
}
}
while (second != nullptr && second->next != nullptr) {
second = second->next;
first = first->next;
}
second->next = head;
head = first->next;
first->next = nullptr;
return head;
}
};
int main() {
ListNode *a = new ListNode(1);
ListNode *b = new ListNode(2);
ListNode *c = new ListNode(3);
ListNode *d = new ListNode(4);
ListNode *e = new ListNode(5);
a->next = b;
b->next = c;
c->next = d;
d->next = e;
Solution s;
ListNode *l = s.rotateRight(a, 2);
while (l != nullptr) {
cout << l->val << ' ';
l = l->next;
}
cout << endl;
}