【LeetCode】24. 两两交换链表中的节点

·  阅读 143

Description

Recursion Linked List


Python

Recursive solution

典型的递归解题思路:关键点在于找最小重复单元

递归的三个部分:

  • 返回值:交换完成的单链表
  • 这一层级做了什么:交换cur和next(cur连接下一级返回的单链表;next连接cur)
  • 终止条件:cur和next其中有一个是None
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        # Recursively
        if not head or not head.next: return head
        new_head = head.next
        head.next = self.swapPairs(new_head.next)
        new_head.next = head
        return new_head
复制代码

Iterative solution

这里如果直接进行交换的话,不方便处理临界条件且不方便最后的return;可以先构造一个前驱node

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        # Iteratively
        pre = ListNode(0, head)
        tmp = pre
        while tmp != None and tmp.next != None and tmp.next.next != None:
            start = tmp.next
            end = start.next
            tmp.next = end
            start.next = end.next
            end.next = start
            tmp = start
        return pre.next
复制代码

END

分类:
代码人生
标签:
收藏成功!
已添加到「」, 点击更改