fueanta

LeetCode 92: Reverse Linked List II

Jul 8th, 2021
1,026
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for singly-linked list.
  3.  * class ListNode {
  4.  *     val: number
  5.  *     next: ListNode | null
  6.  *     constructor(val?: number, next?: ListNode | null) {
  7.  *         this.val = (val===undefined ? 0 : val)
  8.  *         this.next = (next===undefined ? null : next)
  9.  *     }
  10.  * }
  11.  */
  12.  
  13. function reverseBetween(head: ListNode | null, left: number, right: number): ListNode | null {
  14.    
  15.     if (head === null)
  16.         return null;
  17.    
  18.     let currPtr = head, prevPtr = null;
  19.    
  20.     while (left > 1) {
  21.         prevPtr = currPtr;
  22.         currPtr = currPtr.next;
  23.        
  24.         left--;
  25.         right--;
  26.     }
  27.    
  28.     let tailPtr = currPtr, connPtr = prevPtr, thirdPtr: ListNode | null = null;
  29.    
  30.     while (right > 0) {
  31.         thirdPtr = currPtr.next;
  32.         currPtr.next = prevPtr;
  33.         prevPtr = currPtr;
  34.         currPtr = thirdPtr;
  35.        
  36.         right--;
  37.     }
  38.    
  39.     if (connPtr)
  40.         connPtr.next = prevPtr;
  41.     else
  42.         head = prevPtr;
  43.    
  44.     tailPtr.next = currPtr;
  45.    
  46.     return head;
  47. };
  48.  
RAW Paste Data