forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
64 lines (49 loc) · 1.1 KB
/
main.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
/// Source : https://leetcode.com/problems/rotate-list/description/
/// Author : liuyubobobo
/// Time : 2018-03-18
#include <iostream>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Brute Force
/// Two Pointers
///
/// Time Complexity: O(N)
/// Space Complexity: O(1)
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head == NULL)
return NULL;
int len = get_len(head);
k = k % len;
ListNode* end = head;
for(int i = 0 ; i < k ; i ++)
end = end->next;
ListNode* start = head;
while(end->next != NULL){
start = start->next;
end = end->next;
}
end->next = head;
head = start->next;
start->next = NULL;
return head;
}
private:
int get_len(ListNode* head){
int res = 0;
while(head){
res ++;
head = head->next;
}
return res;
}
};
int main() {
return 0;
}