python - Reverse singly linked list in python without using a temporary variable
问题描述
I am trying to solve some problems on Leetcode.
I completed the Reverse Linked List problem, which basically requires you to reverse a singly linked list. My solution is this:
def reverseList(self, head):
curr = head
prev = None
if head != None:
while (curr.next):
temp = curr.next
curr.next = prev
prev = curr
curr = temp
curr.next = prev
return curr
I used a temp value to keep track of the original NEXT node after the current node, before the value of the NEXT node is changed in the following line.
However, when I compare my solution to other solutions, it seems that there was no need for a temporary value at all. Below is a sample solution:
def reverseList(self, head):
curr, prev = head, None
while curr:
curr.next = prev
prev = curr
curr = curr.next
return prev
No temporary value was used, which I am trying to figure out why. The below image is my mental visualisation of what happens in the solution:
Why is it possible for the code to be able to still assign curr = curr.next
(line 4 of solution) after curr.next
was mutated? (line 6 of solution)
解决方案
@lambert 说得对。
您在此处比较的特定解决方案不会逆转任何事情。将链表转换为新变量需要很长时间。
推荐阅读
- scala - 如何根据条件对列表的元素进行分组?
- ruby-on-rails - ActionController::UrlGenerationError: 没有路由匹配 {:action=>"show", :controller=>"demographic_detail", :id=>nil}
- javascript - 在mongodb中将字符串转换为日期?
- sapui5 - 如何在调试器中查看 view.xml 文件?
- java - Json数组不在jsp中打印值
- c++ - 用信号和槽连接多个 UI 对象
- python-3.x - 带有 Python 3.7、pandas 和 scikit-learn (Windows 10) 的 Conda 环境 - 依赖项错误
- ios - Objective c中的自动滚动收集视图
- python - Python 日志记录调试级别不会消失
- php - 仅在标头中禁用缓存