forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseLinkedListII.java
47 lines (41 loc) · 971 Bytes
/
ReverseLinkedListII.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
// TC : O(n)
public ListNode reverseBetween(ListNode head, int left, int right) {
if(head==null || head.next==null){
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
// till the left index
ListNode it = dummy;
ListNode prevIt = null;
for(int i=0;i<left;i++){
prevIt = it;
it = it.next;
}
//reverse
ListNode itR = it;
ListNode prevR = prevIt;
// reversing a linked list
for(int i=left;i<=right;i++){
ListNode forward = itR.next;
itR.next = prevR;
prevR = itR;
itR = forward;
}
//connect
prevIt.next = prevR;
it.next = itR;
return dummy.next;
}
}