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).
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
- LeetCode - Contains Duplicate
- LeetCode - Jewels and Stones
- LeetCode - Climbing Stairs
- Fibonacci Series
- Hackerrank - New Year Chaos
Comments
Post a Comment