Leetcode 143. Reorder List (i dont get it)

whitehousechef·2024년 1월 22일
0

https://leetcode.com/problems/reorder-list/description/

initial

So my initial attempt was placing head first, update head to the right, then add the node which next is None (i.e. the tail) then making that node which next is None as None too.

But it goes on infinite loop

class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        ans = ListNode(0)
        cur = ans
        while True:
            if not head.next:
                break
            cur.next = head
            head = head.next
            tmp = head
            while tmp.next !=None:
                tmp = tmp.next
            cur = cur.next
            cur.next = tmp
            tmp=None
            cur = cur.next
        print(ans)

solution

So kinda the same idea but

I am still not sure how last is updated.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """

        # ----------------------------------------------
        # Save linked list in array

        arr = []

        cur, length = head, 0

        while cur:
            arr.append(cur)
            cur, length = cur.next, length + 1

        # ----------------------------------------------
        # Reorder with two-pointers

        left, right = 0, length - 1
        last = head

        while left < right:
            arr[left].next = arr[right]
            left += 1

            if left == right:
                last = arr[right]
                break

            arr[right].next = arr[left]
            right -= 1

            last = arr[left]

        if last:
            last.next = None

# Function to print a linked list
def print_linked_list(head):
    while head:
        print(head.val, end=" -> ")
        head = head.next
    print("None")

# Example usage:
# Create a sample linked list
sample_list = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))

# Create an instance of Solution and call reorderList
solution = Solution()
solution.reorderList(sample_list)

# Print the modified linked list
print_linked_list(sample_list)

complexity

n time

0개의 댓글