Soohan-Kim / Leetcode

0 stars 0 forks source link

[HW2] Reverse Linked List #206 #24

Open Soohan-Kim opened 5 months ago

Soohan-Kim commented 5 months ago

https://leetcode.com/problems/reverse-linked-list/description/

Soohan-Kim commented 5 months ago
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head

        # Iterative
        # cur = head
        # dummy = ListNode()
        # ret = ListNode(head.val, None)
        # while cur.next:
        #     dummy.val = cur.next.val
        #     dummy.next = ret
        #     ret = dummy
        #     cur = cur.next
        #     dummy = ListNode()
        # return ret

        # Iterative more space efficient (in-place)
        # prev = None
        # while head:
        #     nxt = head.next
        #     head.next = prev
        #     prev = head
        #     head = nxt
        # return prev

        # Recursive
        def reverseEach(cur, prev):
            if not cur:
                head = prev
                return head
            temp = cur.next
            cur.next = prev
            return reverseEach(temp, cur)

        return reverseEach(head, None)