fueanta

LeetCode 206: Reverse Linked List

Jul 7th, 2021
1,421
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 reverseList(head: ListNode | null): ListNode | null {
  14.     let prev: ListNode | null = null;
  15.     let curr = head;
  16.    
  17.     while (curr) {
  18.         let next = curr.next;
  19.         curr.next = prev;
  20.         prev = curr;
  21.         curr = next;
  22.     }
  23.    
  24.     return prev;
  25. };
  26.  
RAW Paste Data