Stack and Queue

Adisak W.1476
1 min readDec 14, 2019

--

Stack, follow the LIFO (Last in First out) principle. Imagine like a one-way slot, the first one to come in, come out last and vice versa.

stack operation

class Stack:
def __init__(self):
self.l = []

def push(self, i):
self.l.append(i)
print("push :", self.l)

def pop(self):
self.l.pop()
print("pop :",self.l)

def peek(self):
print("Last chara :", self.l[(len(self.l) - 1)])
print("Stack :",self.l)

def is_empty(self):
return len(self.l) == 0

def size(self):
print("Length :", len(self.l))

def __str__(self):
return str(self.l)

Queue, follow the FIFO (First in First out) principle. Imagine a queue when you go and buy something.

class Queue:  
def __init__(self):
self.s1 = []
self.s2 = []

def enQueue(self, x):
while len(self.s1) != 0:
self.s2.append(self.s1[-1])
self.s1.pop()
self.s1.append(x)

while len(self.s2) != 0:
self.s1.append(self.s2[-1])
self.s2.pop()

def deQueue(self):
if len(self.s1) == 0:
print("Q is Empty")

x = self.s1[-1]
self.s1.pop()
return x

Conclusion

We can implement stack and queue to many real-world cases. By, understanding how to use them allow us to solve a lot more problems.

--

--

Adisak W.1476
0 Followers

A student at KMITL university ,Thailand.