Skip to content

Instantly share code, notes, and snippets.

@LenarBad
Last active February 8, 2024 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LenarBad/e4d877c4c5276f249c3af7490c47bd3f to your computer and use it in GitHub Desktop.
Save LenarBad/e4d877c4c5276f249c3af7490c47bd3f to your computer and use it in GitHub Desktop.
Reverse Linked List II. Leetcode 92.
/**
* 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