Python Data Structure- Part 2
In the previous article, I have discussed some basic data structure of python. In the article, you will learn about python data structure like stack, queue and dequeue and their implementation.
1. Stack: A stack (sometimes called a “push-down stack”) is an ordered collection of items where the addition of new items and the removal of existing items always takes place at the same end. This end is commonly referred to as the “top.” The end opposite the top is known as the “base.” The ordering principle of stack is called LIFO, last-in-first-out.
eg: stack=[1,’a’,True]
Operation performed on stack:
Implementation of stack:
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)
2. Queue: A queue is an ordered collection of items where the addition of new items happens at one end, called the “rear,” and the removal of existing items occurs at the other end, commonly called the “front.” The ordering principle of queue is called FIFO, first-in-first-out.
eg: queue=[1,’a’, True]
Operation performed on queue:
Implementation of queue:
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
3. Deque: A deque, also known as a double-ended queue, is an ordered collection of items similar to the queue. It has two ends, a front and a rear, and the items remain positioned in the collection. New items can be added at either the front or the rear. Likewise, existing items can be removed from either end.
eg: deque=[1,’a’,True]
Operation performed on deque:
Implementation of deque:
class Deque:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def addFront(self, item):
self.items.append(item)
def addRear(self, item):
self.items.insert(0,item)
def removeFront(self):
return self.items.pop()
def removeRear(self):
return self.items.pop(0)
def size(self):
return len(self.items)
Hope you find this article helpful. Keep learning!