两两交换链表中的节点 两种解法(Python)

两两交换链表中的节点 两种解法(Python),第1张

LeetCode链接

迭代 时间复杂度 O(N)
# 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:
        dummy_head = ListNode()
        dummy_head.next = head
        tmp = dummy_head
        while tmp.next and tmp.next.next:
            node1 = tmp.next
            node2 = tmp.next.next
            tmp.next = node2
            node1.next = node2.next
            node2.next = node1
            tmp = node1
        return dummy_head.next
递归 时间复杂度O(N)
# 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:
        if not head or not head.next:
            return head
        one = head
        two = head.next
        three = head.next.next
        two.next = one
        one.next = self.swapPairs(three)
        return two

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/800466.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-07
下一篇2022-05-07

发表评论

登录后才能评论

评论列表(0条)

    保存