Skip to content

Commit 1b70e72

Browse files
committed
rotate LL
1 parent 80d5686 commit 1b70e72

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed

Striver Sheet/Day-6/Rotate List.cpp

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
Rotate List
3+
===========
4+
5+
Given the head of a linked list, rotate the list to the right by k places.
6+
7+
Example 1:
8+
Input: head = [1,2,3,4,5], k = 2
9+
Output: [4,5,1,2,3]
10+
11+
Example 2:
12+
Input: head = [0,1,2], k = 4
13+
Output: [2,0,1]
14+
15+
Constraints:
16+
The number of nodes in the list is in the range [0, 500].
17+
-100 <= Node.val <= 100
18+
0 <= k <= 2 * 109
19+
*/
20+
21+
/**
22+
* Definition for singly-linked list.
23+
* struct ListNode {
24+
* int val;
25+
* ListNode *next;
26+
* ListNode() : val(0), next(nullptr) {}
27+
* ListNode(int x) : val(x), next(nullptr) {}
28+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
29+
* };
30+
*/
31+
class Solution
32+
{
33+
public:
34+
ListNode *rotateRight(ListNode *head, int k)
35+
{
36+
if (!head || !head->next)
37+
return head;
38+
39+
auto tail = head;
40+
int size = 0;
41+
auto temp = head;
42+
while (temp)
43+
{
44+
size++;
45+
temp = temp->next;
46+
if (tail->next)
47+
tail = tail->next;
48+
}
49+
50+
k = k % size;
51+
52+
if (!k)
53+
return head;
54+
55+
ListNode *dummy = new ListNode(-1);
56+
dummy->next = head;
57+
temp = dummy;
58+
59+
for (int i = 0; i < size - k; ++i)
60+
{
61+
temp = temp->next;
62+
}
63+
64+
head = temp->next;
65+
temp->next = NULL;
66+
tail->next = dummy->next;
67+
return head;
68+
}
69+
};

Striver Sheet/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
- [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) - [Cpp Soultion](./Day-6/Palindrome%20Linked%20List.cpp)
5656
- [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/) - [Cpp Soultion](./Day-6/Linked%20List%20Cycle%20II.cpp)
5757
- [Flattening a Linked List](https://practice.geeksforgeeks.org/problems/flattening-a-linked-list/1#) - [Cpp Soultion](./Day-6/Flattening%20a%20Linked%20List.cpp)
58-
- []() - [Cpp Soultion](./Day-6/.cpp)
58+
- [Rotate List](https://leetcode.com/problems/rotate-list/) - [Cpp Soultion](./Day-6/Rotate%20List.cpp)
5959

6060
###
6161

0 commit comments

Comments
 (0)