Skip to content

206. Reverse 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;
}
}
const first = new ListNode(1);
const second = new ListNode(2);
const third = new ListNode(3);
const fourth = new ListNode(4);
const fifth = new ListNode(5);
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
function reverseList(head: ListNode | null): ListNode | null {
let prev: ListNode | null = null;
let current = head;
while(current) {
const next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
console.log(reverseList(first));