LeetCode 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?

Reference Answer

思路分析

解题方法有很多种:

  1. 借助python list,保存每个节点,再反向遍历,重新链接即可。(时间复杂度 O(n),空间复杂度 O(n))
  2. 进一步优化,直接在进行遍历的时候,保存当前节点,进行反向链接即可,具体看参考代码(此时,时间复杂度O(n),空间复杂度O(1))

Code One
时间复杂度 O(n),空间复杂度 O(n)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        temp_list = []
        while head:
            end = head
            temp_list.append(head)
            head = head.next
        root = end
        for index in range(len(temp_list)-2, -1, -1):
            end.next = temp_list[index]
            end = end.next
        end.next = None
        return root

Code Two
时间复杂度 O(n),空间复杂度 O(1)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        
        real_end = end = head
        # end.next = None
        head = head.next
        while head:
            temp = head
            head = head.next
            temp.next = end
            end = temp
        real_end.next = None
        return end    
        

Note:

  • 注意方法二中,最终要设置 real_end.next = None

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84727372