-1
如何編寫一個函數,如'next(lst)'返回PREVIOUS值而不是NEXT值?從單鏈表到雙鏈表
class EmptyNode():
__slots__ =()
class Node():
__slots__ = ('data', 'next')
class MyList():
"""A class that encapsulates a node based linked list"""
__slots__ = ('head', 'size', 'cursor')
def mkEmptyNode():
return EmptyNode()
def mkNode(data, next):
node = Node()
node.data = data
node.next = next
return node
def mkMyList():
lst = MyList()
lst.head = mkEmptyNode()
lst.size = 0
lst.cursor = mkEmptyNode()
return lst
在鏈表類似['a','b','c']
,next(lst)
將返回'a'
,下一次將返回'b'
,下一次將返回'c'
,並在下一次會返回一個錯誤
def next(lst):
if isinstance(lst.cursor, EmptyNode):
raise IndexError("cursor is invalid")
val = lst.cursor.data
lst.cursor = lst.cursor.next
return val
您在什麼時候創建非空節點?因爲你的'mkMyList'只是創建空節點(它沒有'next'屬性) – BorrajaX