forked from illuz/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAC_simulation_n.cpp
59 lines (52 loc) · 1.26 KB
/
AC_simulation_n.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
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_simulation_n.cpp
* Create Date: 2015-01-02 13:48:41
* Descripton: simulation
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
ListNode *tail = NULL, *cur = head;
int cnt = 0;
// count number
while (cur) {
cnt++;
tail = cur;
cur = cur->next;
}
if (!cnt || !k)
return head;
// k is the count in order
k = cnt - k % cnt;
cur = head;
// find the (k-1)th num
while (--k) {
cur = cur->next;
}
tail->next = head;
head = cur->next;
cur->next = NULL;
return head;
}
};
int main() {
ListNode *head = new ListNode(2);
Solution s;
ListNode *ret= s.rotateRight(NULL, 2);
head->next = new ListNode(3);
head->next->next = new ListNode(6);
head = s.rotateRight(head, 2);
cout << head->val << ' ' << head->next->val << ' '
<< head->next->next->val << endl;
return 0;
}