代码随想录第四天刷题

  1. 第一题:两两交换链表中的值
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy_head = ListNode(next = head)
        current = dummy_head

        while current.next and current.next.next:
            temp = current.next
            temp1 = current.next.next.next

            current.next = current.next.next
            current.next.next = temp
            temp.next = temp1
            current = current.next.next
        
        return dummy_head.next

重点在于

  1. 得是current.next != NULL && current.next.next != NULL 而且顺序不能反。在C++中的写!=NULL,在python中可以直接省略,是因为C++中空值表示的是NULL或者nullptr,python中是None,限免是具体对比,一个是内存,一个是对象

  1. 接下来是设置两个临时指针,这个是区分临时指针及在python中的各个用途:

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务