leetcode206题-反转链表有如下解法:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur,pre = head,None
while cur:
cur.next,pre,cur = pre,cur,cur.next
return pre
对于上述cur.next,pre,cur = pre,cur,cur.next这行代码深感迷惑,查了官方文档给出如下解释:
基于python元组和序列的特性,名为元组封装和序列拆封
其实就是python内部自动给创建了一个temp指针,如下例子:
a,b = 1,3
a,b = b,a
print(a,b)
给出结果为:
3 1
原理就是:
temp_a = a
temp_b = b
a = temp_b
b = temp_a
以上就是个人对其的简单理解,希望大神多多提出问题指正