给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:
-你的算法只能使用常数的额外空间。
-你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
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
dummy=ListNode(0)
#临时应用的链
dummy.next=head
p=dummy
while p.next and p.next.next:
tmp=p.next.next
p.next.next=tmp.next
tmp.next=p.next
p.next=tmp
p=p.next.next
return dummy.next
执行用时: 24 ms, 在Swap Nodes in Pairs的Python提交中击败了99.35% 的用户