Skip to main content

Swap Nodes in Pairs


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


all//Swap Nodes in

# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val = next

class Solution:
def swapPairs(self, head):
if not head or not
return head

dummy = ListNode(0) = head
current = dummy
while and
first_node =
second_node = = = second_node = first_node
current =