LeetCode - Swap Nodes in Pairs Solution - The Coding Shala

Home >> LeetCode >> Swap Nodes in Pairs

LeetCode - Swap Nodes in Pairs Solution

In this post, you will learn how to solve LeetCode's Swap Nodes in Pairs problem with Java Solution. We will solve this problem using recursion and iteration.

Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Practice this problem on LeetCode(Click Here).

Swap Nodes in Pairs Java Solution

Approach 1:
Iterative Solution.
Java Program: 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        //check for null or 1 node
        if(head == null || head.next ==null) return head;
        //prev node need to link after swap so take prev
        ListNode prev = null;
        ListNode curr1 = head;
        ListNode curr2 = head.next;
        ListNode ans = curr2; //head
        //while both the node are not null
        while(curr1 != null && curr2 != null){
            //link prev node to curr2
           if(prev != null ) prev.next = curr2;
            //swap
            curr1.next = curr2.next;
            curr2.next = curr1;
            //change prev
            prev = curr1;
            //change curr1 and curr2
            curr1 = curr1.next;
            if(curr1 != null) curr2 = curr1.next;
        }
        return ans;
    }
}
Approach 2:
Using Recursion.
Java Program: 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;
        
        ListNode second = head.next;
        ListNode third = head.next.next;
        
        second.next = head;
        head.next = swapPairs(third); //find recursivaly
        
        return second;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala