Skip to content

Commit 8f553e2

Browse files
committed
Stack
1 parent 6508a6d commit 8f553e2

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,7 @@ You can implement these notes in your own favourite programming language.
3636
- [x] [KMP (Knuth Morris Pratt) Pattern Searching](Strings/KMP.py)
3737
- [x] [Trees](Trees)
3838
- [x] [Binary Search Tree](Trees/binarysearchtree.py)
39+
- [x] [Stack And Queue](Trees)
40+
- [x] [Stack](Stack-and-Queue/stack.py)
3941

4042
This repository is for the references, anyone can feel free to use this.

Stack-and-Queue/stack.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
'''
2+
Stack
3+
A stack is a linear data structure that follows the principle of Last In First Out (LIFO). This means the last element inserted inside the stack is removed first.
4+
'''
5+
6+
# Stack implementation in python
7+
8+
9+
# Creating a stack
10+
def create_stack():
11+
stack = []
12+
return stack
13+
14+
15+
# Creating an empty stack
16+
def check_empty(stack):
17+
return len(stack) == 0
18+
19+
20+
# Adding items into the stack
21+
def push(stack, item):
22+
stack.append(item)
23+
print("pushed: " + item)
24+
25+
26+
# Removing an element from the stack
27+
def pop(stack):
28+
if (check_empty(stack)):
29+
return "stack is empty"
30+
31+
return stack.pop()
32+
33+
34+
stack = create_stack()
35+
push(stack, str(1))
36+
push(stack, str(2))
37+
push(stack, str(3))
38+
push(stack, str(4))
39+
print("popped: " + pop(stack))
40+
print("After popping: " + str(stack))
41+
42+
'''
43+
pushed: 1
44+
pushed: 2
45+
pushed: 3
46+
pushed: 4
47+
popped: 4
48+
After popping: ['1', '2', '3']
49+
'''

0 commit comments

Comments
 (0)