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.)
Link: https://leetcode.com/problems/swap-nodes-in-pairs/description/
Problem Explanation with examples:-
Example 1
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Explanation: The first pair is swapped. The second pair is swapped.
Example 2
Input: head = []
Output: []
Explanation: The given list is empty (null pointer), so return null.
Example 3
Input: head = [1]
Output: [1]
Explanation: The given list has only one node, so return the same list.
Constraints
The number of nodes in the list is in the range
[0, 100]
.0 <= Node.val <= 100
Intuition:-
Check all the base checks for number of nodes between 0 and 2.
Then move on to taking 3 temporary nodes and keep swapping the links of two nodes in sequence.
Keep track of the first node of the list and return it at the end.
Solution:-
If head is None or head.next is None, return head.
If head.next.next is None, swap the two nodes and return the new head.
Take three temporary nodes x, y and z. x and y are the two nodes to be swapped and z is the node before x.
Initialize x to head, y to head.next and z to head.
Initialize st to y. st will be the new head of the list.
Initialize f to 0. f will be used to check if the first swap has been done or not.
While y is not None, swap the links of x and y. Then move x, y and z to the next nodes.
If f is 1, then set the link of z to y. This is done to link the swapped nodes to the previous nodes.
Set f to 1.
Return st.
Code:-
JAVA Solution
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next == null) return head;
ListNode prev = head;
ListNode curr = head.next;
ListNode lstprev = null;
head = head.next;
while(curr != null){
prev.next = curr.next;
curr.next = prev;
if(lstprev == null)
lstprev = prev;
else{
lstprev.next = curr;
lstprev = prev;
}
prev = prev.next;
if(prev == null) break;
curr = prev.next;
}
return head;
}
}
Python Solution
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
if head.next == None:
return head
if head.next.next == None:
x = head
y = head.next
y.next = x
x.next = None
return y
x = head
y = head.next
z = head
st = y
f = 0
while y:
x.next = y.next
y.next = x
if f:
z.next = y
z = x
x = x.next
if x:
y = x.next
else:
y = None
f = 1
return st
Complexity Analysis:-
TIME:-
The time complexity is O(n) where n is the number of nodes in the list as we are traversing the list only once and swapping the nodes.
SPACE:-
The space complexity is O(1) as we do not use any extra space.