[Python] (Data Structures) Shifting even numbers to the back of a linked list

Discussão em 'Python' iniciado por Stack, Janeiro 31, 2025.

  1. Stack

    Stack Membro Participativo

    I just started my college's data structures and algorithm's course and have been having trouble with shifting nodes of even values to the back of my linked list. For some reason the function seems to work when there's only one even number present, but nothing ends up being printed out otherwise.

    Below is my code (it's a little messy because I've been trying to debug it but I'm failing):

    class Node:
    def __init__(self, data):
    self.data = data
    self.next = None

    class LinkedList:
    def __init__(self):
    self.head = None

    def display(self):
    current = self.head
    while current:
    print(current.data, end = " -> ")
    current = current.next
    print("None")

    def move_even_items_to_back(self):
    # Find the last node
    last_node = self.head
    while last_node.next:
    last_node = last_node.next

    current = self.head
    prev = Node(None)
    prev.next = self.head

    while current:
    if current.data % 2 == 0:
    temp = current.next

    # Add the node to the back
    newNode = Node(current.data)
    newNode.next = None
    last_node.next = newNode
    last_node = last_node.next

    # Moving the previous node
    if prev: # Not the head
    prev.next = current.next
    else: # Move head
    self.head = current.next

    # Removing current node
    current.next = None

    # Moving on
    current = temp

    else:
    prev = current
    current = current.next

    node1 = Node(2)
    node2 = Node(3)
    node3 = Node(4)
    node4 = Node(7)
    node5 = Node(15)
    node6 = Node(18)

    ll = LinkedList()
    ll.head = node1
    node1.next = node2
    node2.next = node3
    node3.next = node4
    node4.next = node5
    node5.next = node6

    ll.display()
    ll.move_even_items_to_back()
    ll.display()



    I've tried to use the current variable and shift it directly to the back, and also to just create a new node with the same value and insert it to the back, and then removing the original node from the list, but both didn't work and nothing ended up being displayed.

    Continue reading...

Compartilhe esta Página