迭代法
    时间复杂度 O(n)

    1. # 反转一个单链表。
    2. #
    3. # 示例:
    4. #
    5. # 输入: 1->2->3->4->5->NULL
    6. # 输出: 5->4->3->2->1->NULL
    7. #
    8. # 进阶:
    9. # 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
    10. # Related Topics 链表
    11. # 👍 1170 👎 0
    12. class ListNode(object):
    13. def __init__(self, x):
    14. self.val = x
    15. self.next = None
    16. # leetcode submit region begin(Prohibit modification and deletion)
    17. # Definition for singly-linked list.
    18. # class ListNode(object):
    19. # def __init__(self, x):
    20. # self.val = x
    21. # self.next = None
    22. class Solution(object):
    23. def reverseList(self, head):
    24. """
    25. :type head: ListNode
    26. :rtype: ListNode
    27. """
    28. pre = None
    29. curr = head
    30. while curr:
    31. tmp = curr.next
    32. curr.next = pre
    33. pre = curr
    34. curr = tmp
    35. return pre
    36. # leetcode submit region end(Prohibit modification and deletion)