程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

(python)小菜狗算法日记(链表系列)_leetcode 206. 反转链表

发布于2020-02-24 22:47     阅读(951)     评论(0)     点赞(23)     收藏(2)


反转一个单链表。

示例:

迭代1笨办法:

  1. class Solution:
  2. def reverseList(self, head: ListNode) -> ListNode:
  3. if not head:
  4. return
  5. p = head
  6. res = []
  7. while(p):
  8. res.append(p.val)
  9. p = p.next
  10. head1 = ListNode(res[-1])
  11. q = head1
  12. res = res[:-1]
  13. while res:
  14. val = res.pop()
  15. q.next=ListNode(val)
  16. q = q.next
  17. return head1

迭代2:代码搬运工,思路是用引入一个指针pre,先让它指向空,迭代中,先把cur.next的值用tmp存下来,然后把cur.next这个指针断开用pre替代,然后pre指针指向cur本身,相当于把往后指的指针往前指惹,最后用后一个节点做cur.

  1. class Solution:
  2. def reverseList(self, head: ListNode) -> ListNode:
  3. cur = head
  4. pre = None
  5. while(cur):
  6. tmp = cur.next
  7. cur.next = pre
  8. pre = cur
  9. cur = tmp
  10. return pre

递归1:代码搬运工,思路是先把cur.next的节点用tmp存,tmp的next接前面反转过的子链表

这个代码思路上行得通,但是会超出时间限制

  1. 输入: 1->2->3->4->5->NULL
  2. 输出: 5->4->3->2->1->NULL

[1,None]   

[2,1,None]

[3,2,1,None]

[4,3,2,1,None]

[5,4,3,2,1,None]

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def reverseList(self, head: ListNode) -> ListNode:
  8. #停止条件:cur遍历到节点最后一个节点(None),返回头节点pre
  9. #返回头节点
  10. def loop(pre,cur):
  11. if not cur:
  12. return pre
  13. tmp = cur.next
  14. cur.next = pre
  15. return loop(cur,tmp)
  16. return loop(None,head)

 

发布了14 篇原创文章 · 获赞 0 · 访问量 1062


所属网站分类: 技术文章 > 博客

作者:爸爸去挣钱我去幼儿园

链接:https://www.pythonheidong.com/blog/article/232626/c364775118d1cc97b142/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

23 0
收藏该文
已收藏

评论内容:(最多支持255个字符)