Stacks

A stack is a linear data structure to store a one-dimensional list. It can store items either in Last-In, First-Out (LIFO) or First-In, Last-Out (FILO) manner. The defining characteristic of a stack is the way elements are added and removed from it. A new element is added at one end and an element is removed from that end only.

Following are the operations related to stacks:

  • isEmpty: Returns true if the stack is empty
  • push: Adds a new element
  • pop: Returns the element added most recently and removes it

The following diagram shows how push and pop operations can be used to add and remove data from a stack:

The top portion of the preceding diagram shows the use of push operations to add items to the stack. In steps 1.1, 1.2, and 1.3, push operations are used three times to add three elements to the stack. The bottom portion of the preceding diagram is used to retrieve the stored values from the stack. In steps 2.2 and 2.3, pop operations are used to retrieve two elements from the stack in LIFO format. 

Let's create a class named Stack in Python, where we will define all of the operations related to the stack class. The code of this class will be as follows:

class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)

To push four elements to the stack, the following code can be used:

Note that the preceding code creates a stack with four data elements.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.121.214