# Swap Nodes In Pairs Program Solution

We at gradjobopenings.com provide free job alerts of freshers job drives. In this website we list on campus job openings for freshers and off campus job openings for freshers and also work from home job openings. This is the best website to apply for off campus drive in India. Visit our website for government job alerts and private job alerts. We also list free interview notes and study materials, one of the best interview study website.comfortable to face the interviews:

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

Example 1:

```Input: head = [1,2,3,4]
Output: [2,1,4,3]
```

Example 2:

```Input: head = []
Output: []
```

Example 3:

```Input: head = [1]
Output: [1]
```

Constraints:

• The number of nodes in the list is in the range `[0, 100]`.
• `0 <= Node.val <= 100`
• Time: O(n)O(n)
• Space: O(1)O(1)

### Swap Nodes In Pairs Program Solution In C++

``````class Solution {
public:
ListNode* prev = &dummy;

for (int i = 0; i < length / 2; ++i) {
ListNode* next = curr->next;
curr->next = next->next;
next->next = prev->next;
prev->next = next;
prev = curr;
curr = curr->next;
}

return dummy.next;
}

private:
int length = 0;
for (ListNode* curr = head; curr; curr = curr->next)
++length;
return length;
}
};
``````

### Swap Nodes In Pairs Program Solution In Java

``````class Solution {
ListNode dummy = new ListNode(0, head);
ListNode prev = dummy;

for (int i = 0; i < length / 2; ++i) {
ListNode next = curr.next;
curr.next = next.next;
next.next = curr;
prev.next = next;
prev = curr;
curr = curr.next;
}

return dummy.next;
}

int length = 0;
for (ListNode curr = head; curr != null; curr = curr.next)
++length;
return length;
}
}
``````

### Swap Nodes In Pairs Program Solution In Python

``````class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
length = 0
length += 1
return length

prev = dummy