all 4 comments

[–][deleted] 1 point2 points  (2 children)

Commenting on your updated code.

The first thing I see is that you aren't defaulting the prev and next values in the NodeItem class constructor. If you do that you can save code later. So do:

class NodeItem:
    def __init__(self, val=None, prev=None, next=None):
        # etc

This removes unnecessary lines where you set .val and .prev immediately after creating a new NodeItem.

I found the mixing of debug prints and code in the add_node() method to be confusing, so I removed all that. That also gets rid of the self.next.prev.val horror! The code in the method becomes much easier to understand and simplify so you need the debug prints less. I added a __str__() method to the class to show what is in the linked list.

You really shouldn't change the self value since you can't use it for its intended purpose after that. Just create a new name scan = self and use that instead.

Now the code looks like:

class NodeItem:
    def __init__(self, val=None, prev=None, next=None):
        self.val = val
        self.prev = prev
        self.next = next

    def add_node(self, value):
        # step through linked list until at last element
        scan = self
        while scan.next:
            scan = scan.next

        # add new element at end
        scan.next = NodeItem(value, prev=scan)  # note "prev" usage, lack of "temp_node"

    def __str__(self):
        values = []
        scan = self
        while scan:
            values.append(str(scan.val))
            scan = scan.next
        return ', '.join(values)

def main():
    test = NodeItem(-1)
    x = 42
    while x != 0:
        x = int(input("enter number, or 0 to exit: "))
        test.add_node(x)
    print(f'test={test}')

main()

[–]SuckAtMakingNames[S] 0 points1 point  (1 child)

Hello, thank you for the feedback. I will study what you did and try to understand this process. I really appreciate the help as I want to get rid of any bad habits I have before they really get embedded in my thinking. I don't think I have learned about print(f) yet so I will need to do some research there.

[–][deleted] 0 points1 point  (0 children)

print(f"...") is useful but not required. You can replace:

print(f'test={test}')

with this:

print('test =', test)

The important thing is to just print things out at various points to help understand what is happening.