206. Reverse Linked List

问题描述

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?

思路

Iteratively的解法,时间、空间复杂度为O(n)。
用tail和head两个指针循环。head在原列表,tail在新列表。

    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return None
        tail = ListNode(head.val)
        tail.next = None
        head = head.next
        while head!= None:
            tmp = ListNode(head.val)
            tmp.next = tail
            tail = tmp
            head = head.next
        return tail  

你可能感兴趣的:(206. Reverse Linked List)