0

I am trying to print linked list with insert function in following order : John Ben Matthew

For whatever reason I am unable to print past "John" even though I am looping using while in the printList() function.

Please see my code below:

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

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

    def insert(self, newNode):
        if self.head is None:
            self.head = newNode
        else:
            lastNode = self.head
            while True:
                if lastNode.next is None:
                    break
                lastNode = lastNode.next
            lastNode.Next = newNode

    def printList(self):
        currentNode = self.head
        while True:
            if currentNode is None:
                break
            print(currentNode.data)
            currentNode = currentNode.next

firstNode = Node("John")
linkedList = LinkedList()
linkedList.insert(firstNode)
secondNode = Node("Ben")
linkedList.insert(secondNode)
thirdNode = Node("Matthew")
linkedList.insert(thirdNode)
linkedList.printList()
jan_w
  • 1

0 Answers0