blue_eclipse
blue_eclipse

Reputation: 9

Remove from the tail of a linked list (Python)

I'm new to Python and am having trouble implementing a function to remove the last node from a linked list. This is the code I have so far (I'm coding on an online platform called Coderunner which already has some background code implemented for me, such as the Node class):

class LinkedList:

    def __init__(self):
        self.head = None

    def print_all(self):
        current = self.head
        while current != None:
            print(current.get_data())
            current = current.get_next()

    def add(self, item): 
        new_node = Node(item)
        new_node.set_next(self.head)
        self.head = new_node      

    def remove_from_tail(self): 
        current = self.head
        prev = current
        while current != None:
            current = current.get_next()
            prev.set_next(current.get_next())
            return current

When running the following code:

my_list = LinkedList() 
my_list.add('Car') 
my_list.add('Bike') 
my_list.add('Truck') 
result = my_list.remove_from_tail() 
print('Removed:', result) 
my_list.print_all()

I get:

Removed: <__main__.Node object at 0x1063650>
Bike
Truck

Can anyone suggest where I've gone wrong? It seems like the node object gets printed but not the value inside the node. Thanks in advance for assistance!

Upvotes: 0

Views: 3312

Answers (2)

Destruktor
Destruktor

Reputation: 463

It looks like this code will remove all nodes from the list. Try something like:

def remove_from_tail(self): 
    current = self.head
    prev = current
    while current.get_next() != None: #the last element will have next == None
        prev = current
        current = current.get_next()
    # At this point, current will be pointing to the last element in the list
    prev.set_next(None)
    return current

Upvotes: 0

amaurs
amaurs

Reputation: 1642

The value that the method remove_from_trail returns is of type Node. When you print it you are printing that Node object. You need to access the value inside the node, you can use:

dir(result) 

to see what methods and attributes does the object have, and then call the attribute that you are looking for.

Upvotes: 0

Related Questions