【Leetcode】206. Reverse Linked List

No206. Reverse Linked List

topic

Reverse a singly linked list.

Example

  • Input: 1->2->3->4->5->NULL
  • Output: 5->4->3->2->1->NULL

Advanced

You can reverse the linked list iteratively or recursively. Can you solve this problem in two ways?

Idea 1

  1. The first traversal, save the data;
  2. The second traverse, change the data;

Problem-solving code (Python3)

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        result = []

        p = head
        while p:
            result.append(p.val)
            p = p.next
        
        p = head
        i = 0
        while p:
            p.val = result[-1-i]
            i += 1
            p = p.next

        return head

Complexity analysis:

  • Time complexity O(n)
  • Space complexity O(n) requires additional space to store elements

operation result

Insert picture description here

Idea 2

Iterate, construct a two-way list of classes to change the direction of the pointer to achieve the goal:

  1. Use pNext to store the next node of the current node
  2. Change head.next to prev, prev to head, and head to pNext

Problem-solving code (Python3)

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        prev = None
        while head:
            pNext = head.next
            head.next,prev,head = prev,head,pNext
        return prev

Complexity analysis

  • Time complexity O(n)
  • Space complexity O(1)

operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/Xiao_Spring/article/details/113760300