题目标题

反转整个链表,要求空间复杂度O(1)

参考解析
  1. 分析:
  2. 在原地一次翻转完成
  3. 循环head链表,将链表中的元素从表头依次取出指向新链表即可。
  4. """
  5. Definition of ListNode
  6. class ListNode(object):
  7. def __init__(self, val, next=None):
  8. self.val = val
  9. self.next = next
  10. """
  11. class Solution:
  12. """
  13. @param head: The first node of the linked list.
  14. @return: You should return the head of the reversed linked list.
  15. Reverse it in-place.
  16. """
  17. def reverse(self, head):
  18. # write your code here
  19. if head is None: return None
  20. p = head
  21. cur = None
  22. pre = None
  23. while p is not None:
  24. cur = p.next
  25. p.next = pre
  26. pre = p
  27. p = cur
  28. return pre