代码随想录第四天刷题
- 第一题:两两交换链表中的值
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
重点在于
- 得是current.next != NULL && current.next.next != NULL 而且顺序不能反。在C++中的写!=NULL,在python中可以直接省略,是因为C++中空值表示的是NULL或者nullptr,python中是None,限免是具体对比,一个是内存,一个是对象
- 接下来是设置两个临时指针,这个是区分临时指针及在python中的各个用途: