-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate_list.cpp
136 lines (123 loc) · 2.53 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/*
* =====================================================================================
*
* Filename: rotate_list.cpp
*
* Description: Rotate List. Given a linked list, rotate the list to the right by k
* places, where k is non-negative.
*
* Version: 1.0
* Created: 02/15/19 07:43:35
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createList(const std::vector<int>& nums)
{
ListNode* head = NULL;
ListNode* p = NULL;
ListNode* n = NULL;
for (size_t i = 0; i < nums.size(); i++)
{
n = new ListNode(nums[i]);
if (i == 0)
{
head = n;
}
else
{
p->next = n;
}
p = n;
}
return head;
}
void deleteList(ListNode* head)
{
ListNode* ptr = NULL;
while (head != NULL)
{
ptr = head->next;
delete head;
head = ptr;
}
}
void printList(ListNode* head)
{
ListNode* ptr = head;
while (ptr != NULL)
{
if (ptr != head)
{
printf(" -> ");
}
printf("%d", ptr->val);
ptr = ptr->next;
}
printf("\n");
}
class Solution
{
public:
ListNode* rotateRight(ListNode* head, int k)
{
int len = 0;
ListNode* prev;
ListNode* node = head;
while (node != NULL)
{
len += 1;
prev = node;
node = node->next;
}
if (len < 1)
{
// Empty list
return head;
}
k %= len;
int pos = len - k;
int idx = 0;
prev->next = head;
node = head;
while (idx < pos)
{
idx += 1;
prev = node;
node = node->next;
}
prev->next = NULL;
return node;
}
};
int main(int argc, char* argv[])
{
std::vector<int> nums = {1, 2, 3, 4, 5};
if (argc > 2)
{
nums.clear();
for (int i = 1; i < argc; i++)
{
nums.push_back(atoi(argv[i]));
}
}
ListNode* head = createList(nums);
printList(head);
head = Solution().rotateRight(head, 2);
printList(head);
deleteList(head);
return 0;
}