Skip to content

Commit 944f8ab

Browse files
Merge pull request #160 from Namanjain6152/rotate-a-linked-list
Rotate a linked list
2 parents 6ebdbe2 + 8d12299 commit 944f8ab

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

0 commit comments

Comments
 (0)