循环反转单链表

  1. class ListNode:
  2. def __init__(self,x):
  3. self.val = x
  4. self.next = None
  5. def list_reverse(head):
  6. if head is None or head.next is None:
  7. return head
  8. pre = None
  9. cur = head
  10. h = head
  11. while cur:
  12. h = cur
  13. tmp = cur.next
  14. cur.next = pre
  15. pre = cur
  16. cur = tmp
  17. return h

递归实现单链表反转

  1. class ListNode:
  2. def __init__(self,x):
  3. self.val = x
  4. self.next = None
  5. def recurse(head,newhead):
  6. if head is None:
  7. return
  8. if head.next is None:
  9. newhead = head
  10. else:
  11. newhead = recurse(head.next,newhead)
  12. head.next.next = head
  13. head.next = None
  14. return newhead

欢迎关注我的微信公众号互相交流

qrcode_for_gh_b8fe229d156f_258 (1).jpg