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
测试是:将给我7
my_list = UnorderedList()
for x in [3,5,4,6,7,8]:
my_list.add(x)
print(my_list.get(1))
我需要编写我的def get(self,index)函数,以便从结尾开始返回索引的值。
我该怎么做?
答案 0 :(得分:0)
你可以试试这个:
for index in range[0, length -1, -1]:
string1 += (length - 1) - index
答案 1 :(得分:0)
假设您的类Node:
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)
更改您的类UnorderedList(这是链接列表):
1,如果要获取链表的大小,请添加函数size
2,你的range
函数不正确,请参考official doc,应该是范围(长度-1,0,-1)
3,对于链表,功能是获取元素而不是索引,你可以搜索并获取元素,直到找到特定元素,见下面的函数get
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return 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 size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.get_next()
return count
def get(self,item):
current = self.head
found = False
string1=""
while current != None and not found:
string1 += str(current)
if current.get_data() == item:
found = True
else:
current = current.get_next()
return string1
测试:
my_list = UnorderedList()
for x in [3,5,4,6,7,8]:
my_list.add(x)
print my_list.get(4)
它会将所有元素添加为链接列表my_list
,然后你可以获得所有元素直到找到4,输出将是:
8764