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;
if (head->next == NULL) return head;
int i = 0, j, arr[101], pass = 0;
while (head != NULL) {
arr[i++] = head->val;
head = head->next;
}
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:
ListNode* swapPairs(ListNode* head) {
if(!head) return head;
if(!head->next) return head;
ListNode* temp =head->next;
int r = temp->val;
temp->val = head->val;
head->val = r;
head->next->next = swapPairs(head->next->next);
return head;
}
};
Solution in Java Programming
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode nxt = head.next;
head.next = swapPairs(nxt.next);
nxt.next = head;
return nxt;
}
// iteratively
public ListNode swapPairs1(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = new ListNode(0), p = head, ret = head.next;
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):
def swapPairs(self, head):
prehead = ListNode(0)
prehead.next = head
prev = prehead
curr = head
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
return prehead.next
Solution in C# Programming
public class Solution {
public ListNode SwapPairs(ListNode head)
{
ListNode current = head;
if(head != null)
{
ListNode prev = head;
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;
if(prev == head)
{
head = current;
}
else
{
prev.next = current;
}
if(current.next == head)
{
head = current;
}
prev = current.next;
current = current.next.next;
}
}
return head;
}
}
Also read,