24. Swap Nodes in Pairs

Post by ailswan Aug.25, 2023

24. Swap Nodes in Pairs

Problem Statement

link: https://leetcode.com/problems/swap-nodes-in-pairs/ https://leetcode.cn/problems/swap-nodes-in-pairs/

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:

Input: 1->2->3->4

Output: 2->1->4->3

Solution Approach

Dummy node switch with first node and second node.

Algorithm

  1. Create a dummy node and attach the head of the linked list to it.
  2. Traverse the list and swap pairs of nodes.
  3. Attach the swapped nodes to the previous node.

Implement

    class ListNode:
        def __init__(self, val=0, next=None):
            self.val = val
            self.next = next

    class Solution:
        def swapPairs(self, head: ListNode) -> ListNode:
            dummy = ListNode(0)
            res = dummy
            dummy.next = head
            while dummy.next and dummy.next.next:
                first = dummy.next
                second = dummy.next.next
                first.next = second.next
                second.next = first
                dummy.next = second
                dummy = dummy.next.next
            return res.next