Last active
February 8, 2024 18:30
-
-
Save LenarBad/e4d877c4c5276f249c3af7490c47bd3f to your computer and use it in GitHub Desktop.
Reverse Linked List II. Leetcode 92.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 { | |
public ListNode reverseBetween(ListNode head, int left, int right) { | |
int count = 1; | |
ListNode prev = null; | |
ListNode curr = head; | |
while (count < left) { | |
prev = curr; | |
curr = curr.next; | |
count++; | |
} | |
ListNode beforeSublist = prev; | |
ListNode lastOfSublist = curr; | |
while (count <= right) { | |
ListNode nextNode = curr.next; | |
curr.next = prev; | |
prev = curr; | |
curr = nextNode; | |
count++; | |
} | |
if (beforeSublist != null) { | |
beforeSublist.next = prev; | |
} else { | |
head = prev; | |
} | |
lastOfSublist.next = curr; | |
return head; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment