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.)
def swapPairs(head):
cur = head
prev = None
new_head = head
while cur and cur.next:
# Save next pair
nn = cur.next.next
# swap cur, cur.next
a = cur
b = cur.next
if prev:
prev.next = b
else:
new_head = b
a.next = b.next
b.next = a
# update prev
prev = cur
cur = nn
return new_head
Comments
Post a Comment