编程语言
首页 > 编程语言> > Leetcode 24. 两两交换链表中的节点 Swap Nodes in Pairs - Python

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

标签:24,pre,Pairs,ListNode,cur,self,next,链表,post
来源: https://blog.csdn.net/rendalian/article/details/123113386