我的代码有问题。代码给出了一个错误,它表示Node在__add __()运算符中没有“previous”但是它在主程序中没有给出错误 赋值的目的是创建一个长的使用链表
class Node(): def __init__(self): self.next = None self.prev = None self.data = None def getData(self): return self.data class LinkedList(): def __init__(self): self.count = 0 self.last = Node() self.first = Node() self.first.next = self.last self.last.previous = self.first def append(self, data): self.last.data = data self.last.next = Node() tmp = self.last self.last = self.last.next self.last.previous = tmp self.count += 1 def prepend(self, data): self.first.data = data self.first.previous = Node() tmp = self.first self.first = self.first.previous self.first.next = tmp self.count += 1 def front(self): if self.count == 0: return None return self.first.next def back(self): if self.count == 0: return None return self.last.previous def size(self): return self.count def __getitem__(self, node): count = self.first while count.data: if count.data == node: return count count = count.next return None def __iter__(self): count = self.first.next while count.data: print("here") yield count.data count = count.next class BigInt: def __init__(self, initValue = "0"): self.data = LinkedList() for count in initValue: self.data.append(count) self.Neg = False def __repr__(self): integer = "" node = self.data.front() while node.next: integer= integer+(node.getData()) node = node.next return "".join(integer) def toString(self): return self.__repr__() def isNeg(self): return self.Neg def __add__(self, rhs): node1 = self.data.back() node2 = rhs.data.back() if self.isNeg() and not rhs.isNeg(): return rhs - self elif rhs.isNeg() and not self.isNeg(): return self - rhs summation = LinkedList() carryOne = 0 print(node1.previous.previous.getData()) while node1.previous.getData() is not None or node2.previous.getData() is not None: tot = int(node1.getData())+int(node2.getData())+carryOne summation.prepend((tot)%10) carryOne = 0 if tot >= 10: carryOne = 1 node1 = node1.previous node2 = node2.previous ret = "" for digit in summation: ret = ret + digit print(digit) print (ret) def __sub__(): pass a = LinkedList() a.prepend(4) a.prepend(5) a.append(23) print (type(a.back())) print(a.back().previous.previous.getData()) g = BigInt("2") h = BigInt("3") (g+h) print (g.toString())
答案 0 :(得分:4)
新构建的previous
中没有Node
成员,只有prev
。
Node
的某些实例稍后将获得名为previous
的成员。这是由于代码如下:
self.last.previous = self.first
(感谢@David Robinson指出这一点。)