-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotate List.cpp
69 lines (64 loc) · 1.07 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
#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(nullptr){}//构造函数
};
class Solution1
{
public:
ListNode *rotateRight(ListNode *head, int k)
{
if (head == nullptr || k <= 0)
return head;
//统计节点个数
int count = 1;
ListNode *pre = head, *cur;
while (pre->next != nullptr)
{
count++;
pre = pre->next;
}
pre->next = head;//此时pre已经指向最后一个节点,串成一个环
k = k % count;
int index = 1;
pre = cur = head;
//右移k位
while (index <= count - k)
{
pre = cur;
cur = cur->next;
++index;
}
pre->next = nullptr;
head = cur;
return head;
}
};
class Solution2
{
public:
ListNode *rotateRight(ListNode *head, int k)
{
if (head == nullptr || k <= 0)
return head;
int len = 1;
ListNode *p = head;
while (p->next != nullptr)//求长度
{
len++;
p = p->next;
}
k = len - k % len;
p->next = head;//首尾相连
for (int step = 0; step != k; ++step)
{
p = p->next;
}
head = p->next;//新的首节点
p->next = nullptr;//断开环
return head;
}
};