File tree 1 file changed +59
-0
lines changed
1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ //T.c -O(n)
2
+ //s.C -O(1)
3
+
4
+ // function used to reverse a linked list
5
+ ListNode* reverse(ListNode* head)
6
+ {
7
+ ListNode* prev = NULL;
8
+ ListNode* curr = head;
9
+ while (curr) {
10
+ ListNode* next = curr->next;
11
+ curr->next = prev;
12
+ prev = curr;
13
+ curr = next;
14
+ }
15
+ return prev;
16
+ }
17
+
18
+ ListNode* reverseBetween(ListNode* head, int left, int right) {
19
+ // function used to reverse a linked list from position m to n
20
+ if (left == right)
21
+ return head;
22
+
23
+ // revs and revend is start and end respectively of the
24
+ // portion of the linked list which need to be reversed.
25
+ // revs_prev is previous of starting position and
26
+ // revend_next is next of end of list to be reversed.
27
+ ListNode*revs = NULL, *revs_prev = NULL;
28
+ ListNode*revend = NULL, *revend_next = NULL;
29
+
30
+ // Find values of above pointers.
31
+ int i = 1;
32
+ ListNode* curr = head;
33
+ while (curr && i <= right) {
34
+ if (i < left)
35
+ revs_prev = curr;
36
+ if (i == left)
37
+ revs = curr;
38
+ if (i == right) {
39
+ revend = curr;
40
+ revend_next = curr->next;
41
+ }
42
+ curr = curr->next;
43
+ i++;
44
+ }
45
+ revend->next = NULL;
46
+ // Reverse linked list starting with revs.
47
+ revend = reverse(revs);
48
+ // If starting position was not head
49
+ if (revs_prev)
50
+ revs_prev->next = revend;
51
+ // If starting position was head
52
+ else
53
+ head = revend;
54
+ revs->next = revend_next;
55
+ return head;
56
+ }
57
+
58
+
59
+ };
You can’t perform that action at this time.
0 commit comments