Leetcode Swap Nodes in Pairs problem solution

Feb 25, 2023

In the Leetcode Swap Nodes in Pairs problem solution 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.)

Constraints:

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

Solution in C Programming

``````struct ListNode* swapPairs(struct ListNode* head){
if (head == NULL) return NULL;

int i = 0, j, arr[101], pass = 0;
}
for (j = 0; j < i - 1; j += 2) {
int hold = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = hold;
}
struct ListNode *first, *current, *previous = NULL;
while (pass < i) {
current = malloc(sizeof(struct ListNode));
current->val = arr[pass++];
if (pass == 1) first = current;
else previous->next = current;
current->next = NULL;
previous = current;
}
return first;
}``````

Solution in C++ Programming

``````class Solution {
public:
int r = temp->val;

}
};``````

Solution in Java Programming

``````class Solution {
}
return nxt;
}

// iteratively
}
while (p != null && p.next != null) {
ListNode nxt = p.next;
p.next = nxt.next;
nxt.next = p;
pre.next = nxt;
pre = p;
p = p.next;
}
return ret;
}
}``````

Solution in Python Programming

``````class Solution(object):

while curr and curr.next:
temp = curr.next.next
prev.next = curr.next
curr.next.next = curr
curr.next = temp
prev = curr
curr = curr.next

Solution in C# Programming

``````public class Solution {
{
{
ListNode temp = null;
ListNode temp1 = null;

while(current != null && current.next != null)
{
temp = current;
temp1 = current.next;
temp.next = current.next.next;

current = temp1;
current.next = temp;

{
}
else
{
prev.next = current;
}

{
}
prev = current.next;
current = current.next.next;
}
}
}
}``````

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.