因此,我要重写Node类以内置访问器和mutator方法,然后将要更改LinkedStack类以合并这些方法。现在,我已经在Node中编写了方法,但是我只更改了LinkedStack中的peek,并且遇到了以下错误:
AttributeError: 'Node' object has no attribute 'getdata'
我正在尝试使用getdata()作为方法,而不是属性。我以为()会表明它是一种方法。
class Node(object):
def __init__(self, data, next = None):
"""Instantiates a Node with default next of None"""
self.data = data
self.next = next
#Accessors
def getdata(self):
return self.data
def getnext(self):
return self.next
#Mutators
def setdata(self, item):
self.data = item
def setnext(self, pointer):
self.next = pointer
class LinkedStack(object):
""" Link-based stack implementation."""
def __init__(self):
self._top = None
self._size = 0
def push(self, newItem):
"""Inserts newItem at top of stack."""
self._top = Node(newItem, self._top)
self._size += 1
def pop(self):
"""Removes and returns the item at top of the stack.
Precondition: the stack is not empty."""
oldItem = self._top.data
self._top = self._top.next
self._size -= 1
return oldItem
def peek(self):
"""Returns the item at top of the stack.
Precondition: the stack is not empty."""
return self._top.getdata() #This is the thing that's acting like an attribute...
def __len__(self):
"""Returns the number of items in the stack."""
return self._size
def isEmpty(self):
return len(self) == 0
def __str__(self):
"""Items strung from bottom to top."""
# Helper recurses to end of nodes
def strHelper(probe):
if probe is None:
return ""
else:
return strHelper(probe.next) + \
str(probe.data) + " "
return strHelper(self._top)
def main():
# Test implementation
s = LinkedStack()
print "Length:", len(s)
print "Empty:", s.isEmpty()
print "Push 1-10"
for i in xrange(10):
s.push(i + 1)
print "Peeking:", s.peek()
print "Items (bottom to top):", s
print "Length:", len(s)
print "Empty:", s.isEmpty()
print "Push 11"
s.push(11)
print "Popping items (top to bottom):",
while not s.isEmpty(): print s.pop(),
print "\nLength:", len(s)
print "Empty:", s.isEmpty()
main()
很抱歉,有很多代码需要梳理...