* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Download CHAPTER 18 Linked Lists, Stacks, Queues, and Priority
Survey
Document related concepts
Transcript
Since the elements are appended and retrieved from the end in a stack, using a list to store the elements of a stack is efficient. The Stack class can be defined as shown in Figure 18.16 and it is implemented in Listing 18.7. Stack -elements: list A list to s tore the elements in th e stack. Stack() isEmpty(): bool peek(): object Constructs an empty stack. Returns true if the stack is empty. Returns the element at the top of the stack without removing it from the stack. Stores an element into the top of the stack. Removes the element at the top of the s tack and returns it. Returns the numb er of elements in the stack. push(value: object): None pop():object getSize(): int Figure 18.16 The Stack class encapsulates the stack storage and provides the operations for manipulating the stack. Listing 18.7 Stack.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class Stack: def __init__(self): self.__elements = [] # Return true if the tack is empty def isEmpty(self): return len(self.__elements) == 0 # Returns the element at the top of the stack # without removing it from the stack. def peek(self): if self.isEmpty(): return None else: return self.__elements[len(elements) - 1] # Stores an element into the top of the stack def push(self, value): self.__elements.append(value) # Removes the element at the top of the stack and returns it def pop(self): if self.isEmpty(): return None else: 29 © Copyright 2012 by Pearson Education, Inc. All Rights Reserved.