0

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?

MarvMan
  • 41
  • 9
SDG
  • 2,260
  • 8
  • 35
  • 77
  • Are you swapping nodes here instead of the values? How are you updating the new pointers to next after swappinh – Devesh Kumar Singh Jul 13 '19 at 21:01
  • @DeveshKumarSingh can you elaborate on updating the new pointers? How would I code that? – SDG Jul 13 '19 at 21:20
  • Can you actually show us how you build the linkedlist, then I can look into it further – Devesh Kumar Singh Jul 13 '19 at 21:24
  • I don't, this is a leetcode problem: https://leetcode.com/problems/reverse-linked-list/ Everything that I have written, is on this question, including the definition for the LinkedList – SDG Jul 13 '19 at 21:45

0 Answers0