My solution to a “Daily Coding Problem” that I received in my mail today.

Given the head of a singly linked list, swap every two nodes and return its head.

For example, given 1 -> 2 -> 3 -> 4, return 2 -> 1 -> 4 -> 3.

Here’s my solution in,

oneFortyFive() {
    //define the linkedList class with a node
    class Node<T> {
        data: T;
        next: Node<T> | null;
        constructor(val: T) {
            this.data = val;
            this.next = null;
        }
    }
    //create a linkedList
    let headNode = new Node<Number>(1);
    headNode.next = new Node<Number>(2);
    headNode.next.next = new Node<Number>(3);
    headNode.next.next.next = new Node<Number>(4);
    console.log(`Linked list before swap`);
    console.log(headNode);

    //now the solution to the problem

    let newHead = headNode;
    while (newHead.next != null && newHead.next != null) {
        let nextData = newHead.next.data;
        newHead.next.data = newHead.data;
        newHead.data = nextData;
        if (newHead.next.next != null) {
            newHead = newHead.next.next;
        } else {
            break;
        }
    }
    //print it
    console.log(`linked list after pairwise swap`);
    console.log(headNode);
}

Like the blog? Subscribe for updates

As usual, if you find any of my posts useful support me by  buying or even trying one of my apps on the App Store. 

https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *