Multiple Assignment output is not correct

34 Views Asked by At

I am trying to write a program where all the odd linked list nodes are pushed to the start of the linked list followed by the odd ones. What I have is below:

def oddEvenList(self, head: ListNode) -> ListNode:
    sentinel = node1 = head
    node2 = second = head.next
    while node1.next:
        node1.next, node1 = node1.next.next, node1.next
    while node2.next:
        node2.next, node2 = node2.next.next, node2.next

    node1.next = second

    return head

The definition for the linked list class is as below:

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

My input is:

[1, 2, 3, 4, 5]

and my output is:

[1, 3, 5, 2]

What the output should be is:

[1, 3, 5, 2, 4]

Even though I assign second as the head of the second list, I still do not seem to add anything but the very head of the second list to the first list. I am doing the assignment here:

node2 = second = head.next

What am I doing wrong?

0

There are 0 best solutions below