Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 返回存储在该索引位置的节点中的数据值_Python_Linked List - Fatal编程技术网

Python 返回存储在该索引位置的节点中的数据值

Python 返回存储在该索引位置的节点中的数据值,python,linked-list,Python,Linked List,测试结果是:给我7分 my_list=UnorderedList() 对于[3,5,4,6,7,8]中的x: 我的列表。添加(x) 打印(my_list.get(1)) 我需要编写def get(self,index)函数,以便它从末尾开始返回索引值 我该怎么做?您可以尝试以下方法: class UnorderedList: def __init__(self): self.head = None def __str__(self): item = self.head

测试结果是:给我7分

my_list=UnorderedList()
对于[3,5,4,6,7,8]中的x:
我的列表。添加(x)
打印(my_list.get(1))

我需要编写def get(self,index)函数,以便它从末尾开始返回索引值

我该怎么做?

您可以尝试以下方法:

class UnorderedList:
def __init__(self):
    self.head = None

def __str__(self):
    item = self.head
    items = list()
    while item:
        items.append(str(item.get_data()))
        item = item.get_next()    
    return '[' + ' '.join(items) + ']' 

def add(self, item):
    new_node = Node(item)
    new_node.set_next(self.head)
    self.head = new_node

def get(self, index):
    item = self.head
    length = item.size()
    string1 = " "
    for index in range[0, length -1, -1]:
        string1 += index

假设您的类节点:

for index in range[0, length -1, -1]:
    string1 += (length - 1) - index
更改类无序列表(这是链接列表):

1、如果要获取链表的大小,请添加函数
size

2、您的
范围
函数不正确,请参考,应该是类似范围(长度-1,0,-1)

3、对于链表,功能是不通过索引获取元素,您可以搜索并获取元素,直到找到特定元素,请参见下面的函数
get

class Node:
    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next

    def set_data(self,newdata):
        self.data = newdata

    def set_next(self,newnext):
        self.next = newnext

    def __str__(self):
        return str(self.data)
测试:

它会将所有元素添加到一个链表
my_list
,然后您可以获取所有元素,直到找到4为止,输出为:

my_list = UnorderedList()
for x in [3,5,4,6,7,8]:
    my_list.add(x)
print my_list.get(4)

我不知道该怎么办,因为我遇到了一个错误:“Node”对象没有属性“size”,我也不能使用len()。我必须在某个地方添加一些东西吗?你可以尝试将my_列表转换为nodelist。那你可以用我的长度
my_list = UnorderedList()
for x in [3,5,4,6,7,8]:
    my_list.add(x)
print my_list.get(4)
8764