题目
思路
一是要添加一个头结点,
二是一定要画图,画图,画图,画图才可以帮助理解这个next指针是如何修改的。
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
pre,cur = dummy,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 dummy.next
运行结果
55 / 55 test cases passed.
Status: Accepted
Runtime: 40 ms