Difficulty: 🟡 Medium
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]
- The number of nodes in the list is in the range
[0, 100]
. 0 <= Node.val <= 100
Python 3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
prev, curr, new_head = None, head, head.next
while curr and curr.next:
temp = curr.next
if prev: prev.next = temp
curr.next, temp.next = temp.next, curr
prev, curr = curr, curr.next
return new_head
The given solution provides an iterative approach to swap every two adjacent nodes in the linked list.
Here is a step-by-step overview of the solution:
- Check if the given linked list is empty or contains only one node. If so, return the head as it is.
- Initialize three pointers:
prev
to keep track of the previous node,curr
to keep track of the current node, andnew_head
to store the new head of the modified list. - Assign the
new_head
as the second node in the original list (head.next
). - Enter a loop to swap every two adjacent nodes:
- Store the reference to the next node after
curr
in the variabletemp
. - If
prev
is notNone
, updateprev.next
to point totemp
. - Swap the positions of
curr
andtemp
by updating thenext
pointers accordingly:curr.next
becomestemp.next
, andtemp.next
becomescurr
. - Update
prev
tocurr
andcurr
to the next node (curr.next
).
- Store the reference to the next node after
- Return the
new_head
, which is the head of the modified list.
The time complexity for this solution is O(n), where n is the number of nodes in the linked list. We visit each node once and perform constant time operations.
The space complexity is O(1) because we are using a constant amount of additional space to store the pointers.
The given solution provides an iterative approach to swap every two adjacent nodes in a linked list. It maintains three pointers to keep track of the previous node, the current node, and the new head of the modified list. The solution runs in linear time and constant space complexity.
NB: If you want to get community points please suggest solutions in other languages as merge requests.