Skip to content

Commit d957a2c

Browse files
Merge pull request PawanJaiswal08#28 from Vartika-Kulshreshtha/rotate-list
Create 61. Rotate List
2 parents dec52b4 + c4f6a8d commit d957a2c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

61. Rotate List

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* rotateRight(ListNode* head, int k) {
14+
ListNode* curr = head;
15+
int len = 1;
16+
17+
while(head == NULL || head -> next == NULL || k==0)
18+
return head;
19+
while(curr -> next != NULL)
20+
{
21+
len++;
22+
curr = curr -> next;
23+
}
24+
curr -> next = head;
25+
k = k % len;
26+
k = len - k;
27+
while(k-- > 0)
28+
{
29+
curr = curr -> next;
30+
}
31+
head = curr -> next;
32+
curr -> next = NULL;
33+
34+
return head;
35+
}
36+
};

0 commit comments

Comments
 (0)