我正在尝试在Python中实现单向链表。这是我_Node课:
#!/usr/bin/env python3
class _Node:
"""Node class to create new nodes"""
def __init__(self, data=None, next=None):
"""Construction of node"""
self._data = data
self._next = next
我已经从这个代码示例中删除了push((,pop((和其他方法。他们都在工作。
class LinkedList:
"""Singly Linked List implementation for storage"""
def __init__(self):
"""Construction of Linked List"""
self._head = None
self._size = 0
def __len__(self):
"""Return length of linked list."""
self._count = 0
self._current = self._head
while self._current:
self._count += 1
self._current = self._current._next
return self._count
def value_at(self, index):
"""Return Value at given index"""
self._current = self._head
self._index = index
count = ans = 0
while count<= self._index:
if self._current == None:
return "List is empty."
ans = self._current._data
self._current = self._current._next
count += 1
return ans
def value_n_from_end(self, n):
"""Get value of nth element starting from end"""
self.n=n
self.n = int(self.__len__() - self.n -1)
print(self.n) #print value as expected
self.value_at(self.n)
现在我的问题是我可以从value_at()
那里获得价值,但无法从类外value_n_from_end()
获得价值。 输入:-
l = LinkedList()
print(l)
print(l.__len__())
print(l.value_at(1))
print(l.value_n_from_end(2))
输出:-
5-> 3-> 4-> 6-> //My Linked List
4 //Length of linked list
3 //Value return by l.value_at(1)
1 //This is the value which i want to pass in self.value_at(self.n)
None //This is returned from (l.value_n_from_end(2))
l.value_n_from_end(2)
的值应与l.value_at(1)
相同,即 3。但我错过了一些东西。
value_n_from_end
不返回任何内容。你应该写:
return self.value_at(self.n)
实际上,self.value_at(self.n)
在函数value_n_from_end
中返回您想要的内容,但随后您必须使用 return 语句将其返回给您。否则,它将绑定到函数命名空间。