Reverse Linked List
Given the head of a singly linked list, reverse the list in-place and return the new head.
Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Explanation: The links are reversed one by one.
export class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val ?? 0;
this.next = next ?? null;
}
}
export function reverseList(head: ListNode | null): ListNode | null {
let prev: ListNode | null = null;
let current = head;
while (current !== null) {
const nextTemp = current.next; // store next node
current.next = prev; // reverse pointer
prev = current; // move prev forward
current = nextTemp; // move current forward
}
return prev;
}