File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ https://leetcode.com/problems/rotate-list/submissions/
3
+ */
4
+ /**
5
+ * Definition for singly-linked list.
6
+ * struct ListNode {
7
+ * int val;
8
+ * struct ListNode *next;
9
+ * };
10
+ */
11
+
12
+
13
+ struct ListNode * rotateRight (struct ListNode * head , int k ) {
14
+ if (!head || k == 0 ) return head ;
15
+
16
+ /*
17
+ Used to count the size of the array.
18
+ */
19
+ struct ListNode * lastNode = head ;
20
+ int n = 1 ;
21
+ while (lastNode -> next )
22
+ {
23
+ lastNode = lastNode -> next ;
24
+ n ++ ;
25
+ }
26
+
27
+ /*
28
+ Used to remove any complete rotations from the list.
29
+ Example: If size of list is n, and no. of rotations = k
30
+ if (n==k)
31
+ then no rotations is required.
32
+ so n = n%k removes all complete roations.
33
+ */
34
+ k = k %n ;
35
+ if (k == 0 ) return head ;
36
+ k = n - k ;
37
+
38
+ lastNode -> next = head ;
39
+ struct ListNode * newHead = head ;
40
+
41
+ for (int i = 0 ; i < k - 1 ; i ++ )
42
+ newHead = newHead -> next ;
43
+
44
+ head = newHead -> next ;
45
+ newHead -> next = NULL ;
46
+ return head ;
47
+ }
You can’t perform that action at this time.
0 commit comments