How to reverse a singly linked list in-place in TypeScript

1 Answer

0 votes
// Node class for singly linked list
class ListNode {
    value: number;          // data stored in the node
    next: ListNode | null;  // reference to the next node

    constructor(value: number) {
        this.value = value;
        this.next = null;
    }
}

// Reverse the linked list in-place
function reverseList(head: ListNode | null): ListNode | null {
    let prev: ListNode | null = null;       // will become the new head
    let current: ListNode | null = head;    // pointer to traverse the list

    while (current !== null) {
        const nextNode: ListNode | null = current.next; // save next node
        current.next = prev;                            // reverse the link
        prev = current;                                 // move prev forward
        current = nextNode;                             // move current forward
    }

    return prev; // prev is the new head
}

// Print the linked list
function printList(head: ListNode | null): void {
    let temp: ListNode | null = head;
    let output: string = "";

    while (temp !== null) {
        output += temp.value;
        if (temp.next !== null) output += " -> ";
        temp = temp.next;
    }

    console.log(output);
}

// Build a sample list: 1 -> 2 -> 3 -> 4 -> 5
let head: ListNode = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);

console.log("Original list:");
printList(head);

// Reverse the list
head = reverseList(head)!;

console.log("Reversed list:");
printList(head);



/*
run:

Original list:
1 -> 2 -> 3 -> 4 -> 5
Reversed list:
5 -> 4 -> 3 -> 2 -> 1

*/

 



answered Jun 30 by avibootz
...