Swap Nodes in Pairs LeetCode Solution

Here, We see Swap Nodes in Pairs problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

Swap Nodes in Pairs LeetCode Solution

Swap Nodes in Pairs LeetCode Solution

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
fig-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)