self.next = None如何获得l1的下一个值? [英] How does self.next = None get the next value of l1?

查看:520
本文介绍了self.next = None如何获得l1的下一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Leetcode上的一个问题(问题21).它要求我合并两个排序的链表,并将其作为新列表返回,并提供这样的预键入代码.

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

在正式解决合并问题之前,我做了一些测试.我输入l1如下:

I did some test before formally solving merging problem. I input l1 as following:

l1 = [1,2,3,4,5]

然后我将代码更改为:

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        print(l1.val)
        print(l1.next.val)

输出显示:

1
2

让我感到困惑的部分是函数self.next如何获取我输入的ListNode的下一个值.以我的理解,self.next设置为None,所以l1.next应该等于None,并且None.val应该出错.有人可以帮我吗?

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.

在此处输入图片描述

此外,这是我遇到问题的链接. https://leetcode.com/problems/merge-two-sorted-列表/#/说明

Also, here is the link where I get my problem. https://leetcode.com/problems/merge-two-sorted-lists/#/description

推荐答案

在新的ListNode中,Nonenext的默认值.其他ListNode可以将其他值分配给next.构造ListNodes的正确 linked 列表涉及为每个节点的link参数分配对下一个节点的引用:

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

这篇关于self.next = None如何获得l1的下一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆