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]
Constraints:
[0, 100]
.0 <= Node.val <= 100
To solve the “Swap Nodes in Pairs” problem, you can follow these steps:
prev
, current
, and next
.prev.next
to point to the second node in the pair (next
).current.next
to point to the node after the pair (next.next
).next.next
to point to the first node in the pair (current
).prev
, current
, and next
pointers to their next positions for the next pair.dummy.next
as the new head of the modified linked list.class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head):
# Initialize a dummy node
dummy = ListNode(0)
dummy.next = head
prev = dummy
# Iterate through pairs
while head and head.next:
# Initialize pointers
current = head
next_node = head.next
# Swap pairs
prev.next = next_node
current.next = next_node.next
next_node.next = current
# Move pointers for the next pair
prev = current
head = current.next
# Return modified head
return dummy.next
# Example Usage:
solution = Solution()
# Example 1:
head1 = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
result1 = solution.swapPairs(head1) # Output: ListNode(2, ListNode(1, ListNode(4, ListNode(3))))
# Example 2:
head2 = None
result2 = solution.swapPairs(head2) # Output: None
# Example 3:
head3 = ListNode(1)
result3 = solution.swapPairs(head3) # Output: ListNode(1)
This code defines a Solution
class with a method swapPairs
that takes a linked list as input and swaps every two adjacent nodes. The example usage demonstrates how to create an instance of the Solution
class and call the swapPairs
method with different inputs.