We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 37dc414 commit b326d5dCopy full SHA for b326d5d
10 August Rotate a Linked List
@@ -0,0 +1,37 @@
1
+class Solution
2
+{
3
+ public:
4
+ //Function to rotate a linked list.
5
+ Node* rotate(Node* head, int k)
6
+ {
7
+ // Your code here
8
+ if (head == nullptr || head->next == nullptr) return head;
9
+ if (k==0) return head;
10
+
11
+ Node *newHead = head;
12
+ Node *prv = nullptr;
13
14
+ while (newHead!=nullptr || k>=0){
15
16
+ if(k==0){
17
+ prv->next = nullptr;
18
+ break;
19
+ }
20
21
+ prv = newHead;
22
+ newHead = newHead->next;
23
+ k--;
24
25
26
+ if (newHead == nullptr) return head; // when k>=N
27
28
+ Node *ptr = newHead;
29
30
+ while (ptr!=nullptr && ptr->next!=nullptr){
31
+ ptr = ptr->next;
32
33
+ ptr->next = head;
34
35
+ return newHead;
36
37
+};
0 commit comments