美文网首页
206. Reverse Linked List

206. Reverse Linked List

作者: JERORO_ | 来源:发表于2018-08-10 19:04 被阅读0次

    问题描述

    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

          本文链接:https://www.haomeiwen.com/subject/rzplbftx.html