python-3.x - 反转链接列表时循环链接列表错误?
问题描述
我在尝试反转链表时遇到链表错误循环-
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
first = head
second = head.next
third = head.next.next
while third != None and third.next != None:
third = second.next
second.next = first
first = second
second = third
print(first)
print (second)
return second
输出:[5]
错误是-
错误 - 在 ListNode ListNode {val: 5, next: None} 中找到循环
解决方案
如果你仔细观察:
third = second.next
“第三”值永远不会改变
反向列表应该如何?
通常在反向链接列表中,头部变为尾部,反之亦然,下一个值指向上一个链接
推荐阅读
- angularjs - 如何在angular js中实现显示更多按钮
- r - 在R中不同长度的两个向量中查找匹配值
- javascript - 如何比较 ComponentDidUpdate 中与 Redux 连接的大型数据结构的 props
- java - Implement a decimal from a String into a Stack
- r - 从日期/时间格式中提取时间
- apache-spark - 将 toEpochDate 与带有 Spark Scala 的数据框一起使用的语法 - 优雅
- android - react native - AWS + React native 使用图像注册
- php - 选择重复 uid 的最新记录
- knockout.js - 如何在不使用计算的 observables 的情况下将可观察数组上的 Knockout foreach 一次限制为 5 个?
- sql-server - 忽略字段中的换行符