I have written code for this leetcode problem :-
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. For example :
Input: head = [1,2,3,4,5], left = 2, right = 4 Output: [1,4,3,2,5]
Following is my code :
public ListNode reverseBetween(ListNode head, int left, int right) {
if(head == null || head.next == null) {
return head;
}
ListNode first = head;
ListNode second = head.next;
ListNode prev = head;
int i = 1;
while( second != null ) {
ListNode nxt = second.next;
if( i == left ) {
ListNode temp = first;
while( i < right ) {
second.next = first;
first = second;
second = nxt;
if( nxt == null ) {
break;
}
nxt = second.next;
i++;
}
if( left == 1 ){
temp.next = second;
head = first;
return head;
}
if( second == null ){
prev.next = first;
temp.next = null;
return head;
}
prev.next = first;
temp.next = second;
return head;
}
else {
prev = first;
first = second;
second = nxt;
}
i++;
}
return head;
}
Although it works, I feel like it is not good enough and can be improved. Any suggestions for any kind of improvements that can be made ?