451. 两两交换链表中的节点
给一个链表,两两交换其中的节点,然后返回交换后的链表。
样例
给出 1->2->3->4
, 你应该返回的链表是 2->1->4->3
。
挑战
你的算法只能使用常数的额外空间,并且不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
实现代码:
"""
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
dummy = ListNode(0)
dummy.next = head
pre = dummy
while pre.next and pre.next.next:
#交换结点
tmp = pre.next.next
pre.next.next = tmp.next
tmp.next = pre.next
#更新结点
pre.next = tmp
pre = pre.next.next
return dummy.next