[Python] Inserting Into Linked List Python

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I've create a pretty standard linked list in python with a Node class and LinkedList class. I've also added in methods for LinkedList as follows:

    1. add(newNode): Adds an element to the linked list
    2. addBefore(valueToFind, newNode): Adds a new node before an element with the value specified.
    3. printClean: Prints the linked list

    I'm trying to use the addBefore method to perform an insertion, however it will not work if the insertion isn't on the head. I'm not sure why.

    class Node:
    def __init__(self, dataval =None):
    self.dataval = dataval
    self.nextval = None

    class LinkedList:
    def __init__(self, headval =None):
    self.headval = headval

    def add(self, newNode):
    # The linked list is empty
    if(self.headval is None):
    self.headval = newNode
    else:
    # Add to the end of the linked list
    currentNode = self.headval
    while currentNode is not None:
    # Found the last element
    if(currentNode.nextval is None):
    currentNode.nextval = newNode
    break
    else:
    currentNode = currentNode.nextval


    def addBefore(self, valueToFind, newNode):
    currentNode = self.headval
    previousNode = None
    while currentNode is not None:
    # We found the element we will insert before
    if (currentNode.dataval == valueToFind):
    # Set our new node's next value to the current element
    newNode.nextval = currentNode

    # If we are inserting at the head position
    if (previousNode is None):
    self.headval = newNode
    else:
    # Change previous node's next to our new node
    previousNode.nexval = newNode
    return 0

    # Update loop variables
    previousNode = currentNode
    currentNode = currentNode.nextval
    return -1

    def printClean(self):
    currentNode = self.headval
    while currentNode is not None:
    print(currentNode.dataval, end='')
    if(currentNode.nextval != None):
    print("->", end='')
    currentNode = currentNode.nextval
    else:
    return

    testLinkedList = LinkedList()
    testLinkedList.add(Node("Monday"))
    testLinkedList.add(Node("Wednesday"))
    testLinkedList.addBefore("Wednesday", Node("Tuesday"))
    testLinkedList.printClean()


    Monday->Wednesday
    ​

    Continue reading...

Compartilhe esta Página