Last updated on February 22nd, 2024 at 03:45 am
Here, We see Swap Nodes in Pairs LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.
List of all LeetCode Solution
![Swap Nodes in Pairs LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Swap Nodes in Pairs LeetCode Solution
Table of Contents
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.)
![Swap Nodes in Pairs ex1](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2022/12/Swap-Nodes-in-Pairs-ex1.jpg?resize=422%2C222&ssl=1)
Example 1: (fig-1) Input: head = [1,2,3,4] Output: [2,1,4,3]
Example 2: Input: head = [] Output: [] Example 3: Input: head = [1] Output: [1]
Swap Nodes in Pairs Leetcode Solution C++
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head || !head->next) return head;
ListNode* temp;
temp = head->next;
head->next = swapPairs(head->next->next);
temp->next = head;
return temp;
}
};
Code language: C++ (cpp)
Swap Nodes in Pairs Leetcode Solution Java
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode prevNode = new ListNode(0);
prevNode.next = head;
ListNode newHead = prevNode;
while(prevNode.next!=null && prevNode.next.next!=null){
ListNode node1 = prevNode.next;
ListNode node2 = node1.next;
ListNode nextNode = node2.next;
prevNode.next = node2;
node2.next = node1;
node1.next = nextNode;
prevNode = node1;
}
return newHead.next;
}
}
Code language: Java (java)
Swap Nodes in Pairs Leetcode Solution JavaScript
var swapPairs = function(head) {
if(!head || !head.next) return head;
var v1 = head, v2 = head.next, v3 = v2.next;
v2.next = v1;
v1.next = swapPairs(v3);
return v2;
};
Code language: JavaScript (javascript)
Swap Nodes in Pairs Leetcode Solution Python
class Solution(object):
def swapPairs(self, head):
pre, pre.next = self, head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next = b, a, b.next
pre = a
return self.next
Code language: Python (python)