This definition initialise a listnode without a next value, it is very clunky to use in recursion
class ListNode:
def __init__(self, x):
self.val = x
self.next = NoneI think the following init function is much more friendly
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = nextSo if you are creating a list of 1 -> 2 -> 3, you can simply type:
ListNode(1, Listnode(2, ListNode(3, None)))Without having to create an empty list-node, then setting up its values. In recursive solutions having to break out of it to manually create an empty node, fill in its value, then filling its next field is very annoying. The above fix would not break any existing code, and is generally a great quality of life improvement considering the vast number of listnode problems in l33tcode. . . honestly just because of this inconvinience each time I see a list problem I get a headache.
For now I use the following work-around
def lnode(x, next):
ret = ListNode(x)
ret.next = next
return ret