发布于2020-03-20 10:57 阅读(1720) 评论(0) 点赞(28) 收藏(2)
cur
是现在的链表节点,tmp
暂存cur.next
,new_head
指向之前的cur
tmp
是保存之前的链条不能断的,很重要class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
# 用三个指针来解决链表反转,cur是现在的链表节点,tmp暂存cur.next,new_head指向之前的cur
cur = head
tmp = None
new_head = None
while cur:
tmp = cur.next
cur.next = new_head
new_head = cur
cur = tmp
return new_head
def reverse_list2(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
# 通过Node指向之前的head来进行链表反转
Node = None
while head:
p = head
head = head.next
p.next = Node
Node = p
return Node
def reverse_list_recusive(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
# 递归反转链表,递归:从下一级的节点指向上一级节点,上一级节点指向None,重复这个过程,直到递归结束
NewHead = self.reverse_list_recusive(head.next)
head.next.next = head
head.next = None
return NewHead
if __name__ == "__main__":
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n1.next = n2
n2.next = n3
n3.next = n4
new_head = Solution().reverse_list(n1)
print(new_head.val)
print(new_head.next.val)
print(new_head.next.next.val)
print(new_head.next.next.next.val)
print()
new_head = Solution().reverse_list2(new_head)
print(new_head.val)
print(new_head.next.val)
print(new_head.next.next.val)
print(new_head.next.next.next.val)
print()
new_head = Solution().reverse_list_recusive(new_head)
print(new_head.val)
print(new_head.next.val)
print(new_head.next.next.val)
print(new_head.next.next.next.val)
这道题很经常的出现在各个厂的笔试题和面试题中,平时大家估计很少用链表,但是面试经常考,所以也要注意下链表的性质,和怎么反转链表
作者:dfd323
链接:https://www.pythonheidong.com/blog/article/270866/7a895fc0179e9e291f68/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!