File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
CPP/Problems/rotate-linkedList Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ <!-- reverse linked list logic iterative -->
2
+ ListNode* reverse(ListNode* head){
3
+ if(!head||!head->next) return head;
4
+ ListNode* next=NULL, * curr=head, * prev= NULL;
5
+ while(curr){
6
+ next=curr->next;
7
+ curr->next=prev;
8
+ prev=curr;
9
+ curr=next;
10
+ }
11
+ return prev;
12
+ }
13
+
14
+ <!-- rotate a linked list by k in right -->
15
+ ListNode* rotateRight(ListNode* head, int k) {
16
+ if(!head||!head->next) return head;
17
+ ListNode* length= head;
18
+ int len=0;
19
+ while(length){
20
+ length=length->next;
21
+ len++;
22
+ }
23
+
24
+
25
+ ListNode* fast= head,* slow=head;
26
+ int val= k%len;
27
+
28
+ while(fast&&val>0){
29
+ fast=fast->next;
30
+ val--;
31
+ }
32
+ if(fast==NULL){
33
+ return reverse(head);
34
+ }
35
+ while(fast->next!=NULL){
36
+ fast=fast->next;
37
+ slow=slow->next;
38
+ }
39
+ fast= slow->next;
40
+ slow->next=NULL;
41
+ slow=head;
42
+ ListNode* first= reverse(slow);
43
+ ListNode* second= reverse(fast);
44
+ ListNode* temp=first;
45
+ while(temp->next){
46
+ temp=temp->next;
47
+ }
48
+ temp->next= second;
49
+ return reverse(first);
50
+ }
You can’t perform that action at this time.
0 commit comments