简体   繁体   中英

Long-double-linked-list

I have a problem with the code. The code gives an error and it says that Node does not have a "previous" in the __add__() operator however it doesnt give an error in the main program The point of the assignment is to create a long using linked list

 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()) 

There's no previous member in a newly-constructed Node , only prev .

Some instances of Node will later acquire a member called previous . This is due to code like:

self.last.previous = self.first

(Thanks to @David Robinson for pointing that out.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM