CODE/Algorithms & Data Structures

[LeetCode] Reverse Linked List

BoriTea 2021. 10. 4. 11:27

 

 

Problem

 

 


 

Solution

 

Iterative:

 

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev = None
        curr = head
        while curr is not None:
            nextNode = curr.next
            curr.next = prev
            prev = curr
            curr = nextNode
        
        return prev

 

Recursive:

 

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return head
        result = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return result

Recursive solution has larger space complexity(O(n)) due to allocating extra space for new linked list on each level.