/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function reverseBetween(head: ListNode | null, left: number, right: number): ListNode | null { if (head === null) return null; let currPtr = head, prevPtr = null; while (left > 1) { prevPtr = currPtr; currPtr = currPtr.next; left--; right--; } let tailPtr = currPtr, connPtr = prevPtr, thirdPtr: ListNode | null = null; while (right > 0) { thirdPtr = currPtr.next; currPtr.next = prevPtr; prevPtr = currPtr; currPtr = thirdPtr; right--; } if (connPtr) connPtr.next = prevPtr; else head = prevPtr; tailPtr.next = currPtr; return head; };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter