How does self.next = None get the next value of l1?

倖福魔咒の 提交于 2019-12-12 03:53:53

问题


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 ListNodes 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!