python-3.xdata-structureslinked-liststack

Stack pop using linked list - Python


I am trying to pop an item off a stack (using a linked list as oppose to an array). I first created a LinkedList class with 3 nodes with the values [1,2,3]. So I would like pop off the last node (node_C, value=3), therefore I expect to see the values [1,2]. Instead nothing prints out.

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

node_A = LinkedList(1)
node_B = LinkedList(2)
node_C = LinkedList(3)

node_A.next = node_B
node_B.next = node_C

def pop(head):
    current_node = head
    while current_node.next:
        if current_node.next == None:
            break
        else:
            current_node = current_node.next

del current_node

return node_A.value, node_B.value, node_C.value

try:
    print(pop(node_A))
except NameError:
    pass

How can I rewrite this to achieve my desired results (i.e. show values 1,2 .. with 3 popped off)?


Solution

  • The del current node and return node_A.value, node_B.value, node_C.value commands should belong to the pop() function, so they should be indented. But anyway the del current node doesn't work for me. Instead you could write current_node.value = None but then you still return all 3 node values so the result would be 1,2,None.

    I would rather write the pop() function inside the class and add another printlist() function to the class as well. The pop() function just removes the last element from the list (changes the next attribute to None for the 2nd last element in the list) and doesn't print or return anything. The printlist() function iterates through the list and prints out all elements (while there are next elements). Here is my code:

    class LinkedList:
        def __init__(self, value):
            self.value = value
            self.next = None
    
        def pop(self):
            current_node = self
            while current_node.next:
                if current_node.next.next == None:
                    current_node.next = None
                else:
                    current_node = current_node.next
    
        def printlist(self):
            current_node = self
            lst = [current_node.value]
            while current_node.next:
                current_node = current_node.next
                lst.append(current_node.value)
            print lst
    
    
    node_A = LinkedList(1)
    node_B = LinkedList(2)
    node_C = LinkedList(3)
    
    node_A.next = node_B
    node_B.next = node_C
    
    try:
        node_A.pop()
        node_A.printlist()
    except NameError:
        pass
    

    If I run this, the result is [1,2]. If I remove the node_A.pop() I get [1,2,3]. If I write another node_A.pop() then result is [1].