Problem Description
You are given a singly linked list. Reverse the list and return it.
The list is represented by the following structure.
typescript
class ListNode {
val: number;
next: ListNode | null;
}Constraints
- The number of nodes in the list is in the range from 1 to 5000
- The value of each node is in the range from -5000 to 5000
Examples
Solution
All we need to do is iterate over all nodes of the linked list and swap the pointers to the next and previous nodes.
typescript
export 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;
}
}
export const reverseList = (head: ListNode | null): ListNode | null => {
let prev: ListNode | null = null;
let curr = head;
while (curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
};Complexity Analysis
Time Complexity
O(n), since we iterate over all nodes of the list.
Space Complexity
O(1), since we don't allocate any additional memory.