Leetcode-206-Reverse Linked List

206. Reverse Linked List (Easy)

Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

1. 思路

核心步骤:

next = cur.next cur.next = pre pre = cur cur = next

2. 代码

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre = None
        cur = head
        while cur:
            _next = cur.next
            cur.next = pre
            pre = cur
            cur = _next
        return pre