0
点赞
收藏
分享

微信扫一扫

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

迭代 时间复杂度 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



举报

相关推荐

0 条评论