DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Tanvir Rahman
Tanvir Rahman

Posted on

Swap Nodes in Pairs - Daily JS (Day 20)

Problem Statement
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Examples
Example 1:

Swap nodes in pairs

Input: head = [1,2,3,4]
Output: [2,1,4,3]
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: head = []
Output: []
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: head = [1]
Output: [1]
Enter fullscreen mode Exit fullscreen mode

Constraints:

The number of nodes in the list is in the range [0, 100].
0 <= Node.val <= 100
Enter fullscreen mode Exit fullscreen mode

Solution

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
const swapPairs = (n) => {
    if (n === null) {
        return null
    }
    if (n.next === null) {
        return n
    }
    let n1 = n.next
    let n2 = n.next.next
    n1.next = n
    n.next = swapPairs(n2)
    return n1
};
Enter fullscreen mode Exit fullscreen mode

LeetCode issue:
https://leetcode.com/problems/swap-nodes-in-pairs/

How to implement a Linked List?

I hope you are enjoying the series, if yes then don't forget to press ❀️ and Follow. You can also bookmark it for later use. If you have any queries or suggestions don't hesitate to drop them.
Thanks will see you in next post.

Top comments (0)

🌱 DEV runs on 100% open source code known as Forem.

Β 
Contribute to the codebase or learn how to host your own.