Skip to content

Commit a502841

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <[email protected]>
1 parent a1c8649 commit a502841

File tree

2 files changed

+62
-17
lines changed

2 files changed

+62
-17
lines changed

0061_rotate_list/rotate_list.c

+14-17
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,29 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33

4+
45
struct ListNode {
56
int val;
67
struct ListNode *next;
78
};
89

9-
static struct ListNode* rotateRight(struct ListNode* head, int k)
10+
struct ListNode* rotateRight(struct ListNode* head, int k)
1011
{
11-
if (head == NULL || k <= 0) {
12+
if (head == NULL) {
1213
return head;
1314
}
1415

16+
int len = 0;
1517
struct ListNode dummy;
1618
dummy.next = head;
17-
struct ListNode *prev = &dummy;
18-
struct ListNode *p = head;
19-
int len = 0;
20-
while (p != NULL) {
21-
prev = p;
22-
p = p->next;
19+
struct ListNode *tail = &dummy;
20+
while (tail->next != NULL) {
21+
tail = tail->next;
2322
len++;
2423
}
2524

26-
struct ListNode *last = prev;
27-
prev = &dummy;
28-
p = head;
25+
struct ListNode *prev = &dummy;
26+
struct ListNode *p = head;
2927
len = len - (k % len);
3028
while (len-- > 0) {
3129
prev = p;
@@ -36,23 +34,22 @@ static struct ListNode* rotateRight(struct ListNode* head, int k)
3634
/* deletion */
3735
prev->next = NULL;
3836
/* insertion */
39-
last->next = dummy.next;
40-
dummy.next = p;
37+
tail->next = head;
38+
head = p;
4139
}
4240

43-
return dummy.next;
41+
return head;
4442
}
4543

4644
int main(int argc, char **argv)
4745
{
48-
int i;
49-
struct ListNode *p, *prev, dummy, *list;
50-
5146
if (argc < 2) {
5247
fprintf(stderr, "Usage: ./test k n1 n2...\n");
5348
exit(-1);
5449
}
5550

51+
int i;
52+
struct ListNode *p, *prev, dummy, *list;
5653
dummy.next = NULL;
5754
prev = &dummy;
5855
for (i = 2; i < argc; i++) {

0061_rotate_list/rotate_list.cc

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* struct ListNode {
8+
* int val;
9+
* ListNode *next;
10+
* ListNode() : val(0), next(nullptr) {}
11+
* ListNode(int x) : val(x), next(nullptr) {}
12+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
13+
* };
14+
*/
15+
class Solution {
16+
public:
17+
ListNode* rotateRight(ListNode* head, int k) {
18+
if (head == nullptr) {
19+
return head;
20+
}
21+
22+
int len = 0;
23+
ListNode dummy;
24+
dummy.next = head;
25+
ListNode *tail = &dummy;
26+
while (tail->next != nullptr) {
27+
len++;
28+
tail = tail->next;
29+
}
30+
31+
ListNode *prev = &dummy;
32+
ListNode *p = head;
33+
k = k % len;
34+
for (int i = 0; i < len - k; i++) {
35+
prev = p;
36+
p = p->next;
37+
}
38+
39+
if (p != nullptr) {
40+
/* deletion */
41+
prev->next = tail->next;
42+
/* insertion */
43+
tail->next = head;
44+
head = p;
45+
}
46+
return head;
47+
}
48+
};

0 commit comments

Comments
 (0)