Issue
The problem I have is with my linked list implementation, it simply does not want to recognize my argument. Let me show you the code to illustrate what I mean:
class Node:
def __init__(self, element:int):
self.element = element
element:int = 0
nextNode = None
class LinkedList:
head:Node = None
def insert(self, element:int):
if self.head == None:
currentNode = Node.__init__(element)
self.head = currentNode
else:
currentNode = self.head
while currentNode.nextNode != None:
currentNode = currentNode.nextNode
newNode = Node.__init__(element)
currentNode.nextNode = newNode
def prettyPrint(self):
currentNode = self.head
print("Current Linked List\n")
while currentNode.nextNode != None:
print(currentNode.element+" ---> ")
currentNode = currentNode.nextNode
def main():
Linkedlist = LinkedList()
Linkedlist.insert(1)
Linkedlist.insert(9)
Linkedlist.insert(2)
Linkedlist.insert(18)
Linkedlist.insert(5)
Linkedlist.insert(8)
Linkedlist.prettyPrint()
if __name__ == '__main__':
main()
The error happens in the insert method at
currentNode = Node.init(element)
I'm new to Python and so any help is appreciated.
Solution
Here is your code with two small fixes:
- Construct a
Node
by callingNode(element)
- in
print
either separate arguments with a,
or useend="something"
to tellprint
to put a"something"
at the end of the output.
class Node:
def __init__(self, element: int):
self.element = element
element: int = 0
nextNode = None
class LinkedList:
head: Node = None
def insert(self, element: int):
if self.head == None:
currentNode = Node(element)
self.head = currentNode
else:
currentNode = self.head
while currentNode.nextNode != None:
currentNode = currentNode.nextNode
newNode = Node(element)
currentNode.nextNode = newNode
def prettyPrint(self):
currentNode = self.head
print("Current Linked List\n")
while currentNode.nextNode != None:
print(currentNode.element, end=" ---> ")
currentNode = currentNode.nextNode
def main():
Linkedlist = LinkedList()
Linkedlist.insert(1)
Linkedlist.insert(9)
Linkedlist.insert(2)
Linkedlist.insert(18)
Linkedlist.insert(5)
Linkedlist.insert(8)
Linkedlist.prettyPrint()
if __name__ == "__main__":
main()
Have fun learning python ;)
Answered By - Michael Kopp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.