24. Swap Nodes in Pairs
Given 1->2->3->4, you should return the list as 2->1->4->3.# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next: return head
n = head.next
head.next = self.swapPairs(head.next.next)
n.next = head
return nLast updated
Was this helpful?