问题
I was working on one of the problems on Leetcode (problem 21). It asks me to merge two sorted linked lists and return it as a new list, and it gives pre-typed code like this.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
I did some test before formally solving merging problem. I input l1 as following:
l1 = [1,2,3,4,5]
and I changed the code into:
class Solution(object):
def mergeTwoLists(self, l1, l2):
print(l1.val)
print(l1.next.val)
The output shows:
1
2
The part that confused me is how does function self.next get the next value of the ListNode that I input. In my understanding, self.next is set to None, so l1.next should equal to None, and None.val should go wrong. Could someone help me with this?
Here are two pictures that show the code, input, and output.
enter image description here
Also, here is the link where I get my problem. https://leetcode.com/problems/merge-two-sorted-lists/#/description
回答1:
That None
is the default value of next
in a new ListNode
. Other ListNode
s can have other values assigned to next
. Constructing a properly linked list of ListNodes
involves assigning to each node's link parameter a reference to the next node:
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(3)
l4 = ListNode(4)
l5 = ListNode(5)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
来源:https://stackoverflow.com/questions/45202225/how-does-self-next-none-get-the-next-value-of-l1