当前位置:   article > 正文

leetcode206-Reverse Linked List反转链表(python)_linked list的反转 python

linked list的反转 python

法1:设置pre, current, next三个指针。时间消耗O(n),空间O(1)   (重点掌握法1即可)

  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. if head==None or head.next==None:
  9. return head
  10. pre=None
  11. cur=head
  12. next=None # tmp临时变量
  13. while cur!=None:
  14. next=cur.next
  15. #交换
  16. cur.next=pre
  17. #更新
  18. pre=cur
  19. cur=tmp
  20. return pre

法2: 设置个辅助数组,将链表值存入数组中,反序数组后转化为链表。时间O(n),空间O(n)

  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. arr=[]
  9. while head:
  10. arr.append(head.val)
  11. head=head.next
  12. newhead=ListNode(0)
  13. tmp=newhead
  14. for item in arr[::-1]:
  15. tmp.next=ListNode(item)
  16. tmp=tmp.next
  17. return newhead.next

 法3:和法1类似,区别是以链表的第二个元素作为循环变量。时间O(n),空间O(1)

  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. if head==None or head.next==None:
  9. return head
  10. p1=head
  11. p2=head.next
  12. tmp=None
  13. while p2:
  14. tmp=p2.next
  15. p2.next=p1
  16. p1=p2
  17. p2=tmp
  18. head.next=None #否则时间超出限制
  19. return p1

法4:递归法。时间O(n),空间O(1)

  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. if head is None or head.next is None:
  9. return head
  10. else:
  11. newhead=self.reverseList(head.next)
  12. head.next.next=head
  13. head.next=None
  14. return newhead

参考:

用python介绍4种常用的单链表翻转的方法

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号