May 2017
Intermediate to advanced
310 pages
8h 5m
English
As we said earlier, we could also add a peek method. This will just return the top of the stack without removing it from the stack, allowing us to look at the top element without changing the stack itself. This operation is very straightforward. If there is a top element, return its data, otherwise return None (so that the behavior of peek matches that of pop):
def peek(self): if self.top return self.top.data else: return None