迭代
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
start = ListNode(0, head)
p1 = start
p2 = start.next
while p1.next and p2.next:
p1.next = p2.next
p2.next = p2.next.next
p1.next.next = p2
p1 = p2
p2 = p2.next
return start.next
递归
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
newhead = head.next
head.next = self.swapPairs(newhead.next)
newhead.next = head
return newhead
总结
1、本题虽然难度中等,但并不难,可用迭代和递归两种方法解答。