1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第二百零六题
(1)题目
英文:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
中文:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
(2)解法
① 递归:先找到最后一个数3,然后依次接2,1,None就完成了
(耗时:56ms,内存:18.5M)
# 同样的代码贴上
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
newH = self.reverseList(head.next)
head.next.next = head
head.next = None
return newH
② 迭代:就是先在表头1下面改接None,然后依次在1的前面接上2,2前面接上3就完成了
(耗时:48ms,内存:14.5M)
# 同样经典代码贴上
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, pre = head, None
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre
注意:
1.cur.next, pre, cur = pre, cur, cur.next
与下面的代码是不等价的!
cur.next = pre
pre = cur
cur = cur.next
要等价,可以等效为:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
因为多变量的赋值是会创建临时变量空间来存放的,所以不会只要是使用相同的变量名称,值都不会变!
2如果要本地测试解法②,直接运行下面的代码即可
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class SingleLinkList:
def __init__(self, node=None):
self.__head = node
def is_Empty(self):
return self.__head is None
def append(self, item):
node = ListNode(item)
if self.is_Empty():
self.__head = node
else:
cur = self.__head
while cur.next is not None:
cur = cur.next
cur.next = node
def find_head(self):
return self.__head
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, pre = head, None
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre
ls = SingleLinkList()
data = [1, 2, 3]
for i in data:
ls.append(i)
print(type(ls))
mm = Solution()
res = mm.reverseList(ls.find_head())
while res:
print(res.val, end='')
res = res.next
3.补充一点
a=1
b=2
c=3
a, b, c = b, a+b, b
#输出
a=2
b=1+2=3
c=b=2