Leetcode 24. 两两交换链表中的节点 Swap Nodes in Pairs - Python

# 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:
        sentinalNode = ListNode(next=head)   #哨兵节点与head链表接头
        pre = sentinalNode

        while pre.next and pre.next.next:  #循环条件 pre的下个和下下个节点存在才有交换的必要
            cur = pre.next
            post = pre.next.next

            cur.next = post.next
            post.next = cur
            pre.next = post

            pre = pre.next.next
        
        return sentinalNode.next

上一篇:深入探析 Rational AppScan Standard Edition 新特性之 Glass Box 扫描


下一篇:luffy项目之多方式登录