https://leetcode-cn.com/problems/swap-nodes-in-pairs/
# -*- coding:utf-8 -*-
# Definition for singly-linked list.
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 head is None:
return
node = head.next
if node is None:
return head
head.next = node.next
node.next = head
head.next = self.swapPairs(head.next)
return node
if __name__ == '__main__':
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n1.next = n2
n2.next = n3
n3.next = n4
print(Solution().swapPairs(n1))
思路:每次交换两个临近的链表,然后向下递归。边界条件就是剩一个节点(总节点数为奇数),直接返回head即可,正好两两交换(这种的话递归的head就为空)直接返回空即可。
0 条评论