猿问

将一个值为 `val` 的节点追加到列表 python3 的末尾

我有一个测试程序需要运行而没有任何错误。我有一个不同的程序定义了这个方法中的方法我需要将一个值为 val 的节点附加到列表的末尾我不知道如何开始,希望任何人都能让我上路!


对于称为 opg1 的方法


class List:

    """ This implements a list using `Node` for its elements """

    class Node:

        """ A node consists of a value (val) and a  next-ptr (lnk) """

        def __init__(self, val, lnk=None):

            self.val = val

            self.lnk = lnk


    def __init__(self, root=None):

        self.root = root


    def append(self, val):

        """ Appends a node with value `val` to the end of the list.

        """ 

这是我需要编写代码来完成测试和测试的地方:


from opg1 import *


# Test for List.append(val)

if __name__ == '__main__':

    l = List()

    l1 = List(List.Node("one"))

    l12 = List(List.Node("one", List.Node("two")))

    l123 = List(List.Node("one", List.Node("two", List.Node("three"))))

    for l, r in [

            ( l, "[four]" ),

            ( l1, "[one,four]" ),

            ( l12, "[one,two,four]" ),

            ( l123, "[one,two,three,four]" ),

            ]:

        l.append("four")

        if l.show() != r:

            print("Error: {} != {}".format(l.show(), r))

    print('End of Tests.')


PIPIONE
浏览 77回答 1
1回答

慕的地8271018

尝试这个:class List:    """ This implements a list using `Node` for its elements """    class Node:        """ A node consists of a value (val) and a  next-ptr (lnk) """        def __init__(self, val, lnk=None):            self.val = val            self.lnk = lnk    def __init__(self, root=None):        self.root = root    def append(self, val):        """ Appends a node with value `val` to the end of the list.        """         if self.root is None:            self.root = List.Node(val)        else:            curr = self.root            while curr.lnk:                curr = curr.lnk            curr.lnk = List.Node(val)# Test for List.append(val)if __name__ == '__main__':    l = List()    l.append('one')    l.append('two')    l.append('three')    print(l.root.val, l.root.lnk.val, l.root.lnk.lnk.val)    print('End of Tests.')输出:one two threeEnd of Tests.
随时随地看视频慕课网APP

相关分类

Python
我要回答