451. Swap Nodes in Pairs
Description:
Given a linked list, swap every two adjacent nodes and return its head.
Example
Given 1->2->3->4, you should return the list as 2->1->4->3.
Challenge
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Code:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: a ListNode
@return: a ListNode
"""
def swapPairs(self, head):
# write your code here
tmp = ListNode(0)
tmp.next = head
pre = tmp
cur = head
while cur and cur.next:
pre.next = cur.next
cur.next = pre.next.next
pre.next.next = cur
pre = cur
cur = cur.next
return tmp.next