forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotate_List.cpp
70 lines (63 loc) · 1.14 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
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 15, 2012
Problem: Rotate List
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
Solution:
O(2n)
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
int count;
ListNode *cur, *newtail, *tail;
if (!head) {
return head;
}
count = 1;
cur = head;
while (cur->next) {
cur = cur->next;
count++;
}
tail = cur;
k = k % count;
cur = head;
count = 0;
while (count < k) {
cur = cur->next;
count++;
}
newtail = head;
while (cur->next) {
cur = cur->next;
newtail = newtail->next;
}
tail->next = head;
head = newtail->next;
newtail->next = NULL;
return head;
}
};