Skip to main content

Swap Nodes in Pairs

Question

Given a linked list, write a function to swap the positions of the nodes in each pair of nodes in the linked list.

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

Solution

all//Swap Nodes in Pairs.py


# 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):
if not head or not head.next:
return head

dummy = ListNode(0)
dummy.next = head
current = dummy
while current.next and current.next.next:
first_node = current.next
second_node = current.next.next
first_node.next = second_node.next
current.next = second_node
current.next.next = first_node
current = current.next.next
return dummy.next