I'm currently self studying some programming and I have stumbled upon a problem that asks you to make a linked list which contains digits of a certain number (from last to first). This is the code that I wrote and i have no idea why it does't work. I've created simple node class and a Number class that will hold my list.
class Node:
def __init__(self, x=None):
self.val = x
self.next = None
def __str__(self):
return str(self.val)
class Number:
def __init__(self):
self.first = None
def set(self, num):
for i in range(len(str(num))):
tail = Node(num % 10)
if i == 0:
head = tail
num //= 10
tail = tail.next
self.first = head
Set function is ment to create a list with given digits, so
n = Number()
n.set(123)
should create a list 3 -> 2 -> 1, but when i try to print it using
def node_printer(head: Node):
while head is not None:
if head.next is not None:
print(str(head) ", ", end="")
else:
print(head)
head = head.next
and calling node_printer(n.first) I get 3 as an output.
CodePudding user response:
At tail = tail.next
since tail
was just created, tail.next
is None
so nothing gets linked.
def set(self, num):
head = tail = None
while num:
# Create new node
temp = Node(num % 10)
# Empty list?
if head == None:
head = tail = temp
# Not empty list, append to tail
else:
tail.next = temp
# Update tail for next time
tail = temp
num //= 10
self.first = head
CodePudding user response:
You could approach this by adding to the head rather than tail. It is much easier to get digits of a number that way too:
def numberList(number):
head = Node(0) # initial head of zero
while number:
number,digit = divmod(number,10) # extract last digit
newHead = Node(digit) # make it a node
newHead.next, head = head, newHead # link it as newHead
return head.next or head # single zero or first digit
You can make this even shorter by adding a nextNode optional parameter to your Node class:
class Node:
def __init__(self, x=None, nextNode=None):
self.val = x
self.next = nextNode
def numberList(number):
head = Node(0) # initial head of zero
while number:
number,digit = divmod(number,10) # extract last digit
head = Node(digit,head) # make it a node, link old head
return head.next or head # single zero or first digit