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

2022/2/24 17:22:33

本文主要是介绍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



这篇关于Leetcode 24. 两两交换链表中的节点 Swap Nodes in Pairs - Python的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程