两两交换链表中的节点python3(leetcode24)

#24. 两两交换链表中的节点

# 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(0)
        dummy_head.next = head
        node0 = dummy_head
        while(node0.next and node0.next.next):
            node1 = node0.next
            node2 = node0.next.next
            node3 = node2.next

            node2.next = node1
            node1.next = node3
            node0.next = node2

            node0 = node0.next.next
        
        return dummy_head.next

猜你喜欢

转载自blog.csdn.net/ziqingnian/article/details/121923047