1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Zigzag Linked List

Discussão em 'Python' iniciado por Stack, Setembro 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have written this function to zigzag a linkedlist. But its running for indefinite time. I checked the loop multiple times. Even for the example i tried doing the iteration on notebook but still i didn't figure out the problem why its running indefinitely.

    # LinkedList() class is already defined in driver code
    # zigzag takes a linkedlist instance and linkedlist.head
    def zigzag(ll, head):
    if head is None or head.next is None:
    return head

    curr = head
    while curr and curr.next and curr.next.next:
    next_node = curr.next
    after_node = curr.next.next
    temp = None
    if after_node.next:
    temp = after_node.next
    curr.next = after_node
    curr.next.next = next_node
    if temp:
    curr.next.next.next = temp
    curr = temp

    return ll


    # << TEST >>
    if __name__ == "__main__":
    ll = LinkedList()
    ll.insert_values([1, 2, 3, 4, 5, 6])
    ll.Print()
    lln = zigzag(ll, ll.head)
    lln.Print()


    expected output : 1 3 2 4 6 5

    Continue reading...

Compartilhe esta Página