File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed
DSA-Python/DataStructures Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ STACK
3
+ LIFO
4
+
5
+ All push and pop operations are to/from the top of the stack
6
+ PUSH an item onto the stack
7
+ POP an item off of the stack
8
+ PEEK to get item on top of stack, without removing it
9
+ CLEAR all items from stack
10
+
11
+ STACK USE CASE
12
+ Undo Command : track which command have been executed. Pop last command off the command stack to undo it
13
+ Calling Function: Function Calling in any programming language is managed using stack
14
+
15
+ Stack Class in Python:
16
+ list
17
+ collections.deque
18
+ queue.LifoQueue
19
+
20
+ BigO of stack:
21
+ Push/Pop element -----> O(1)
22
+ Search element by value -----> O(n)
23
+
24
+ '''
25
+
26
+ ''' CLASS STACK() '''
27
+ class Stack ():
28
+ def __init__ (self ):
29
+ self .stack = list ()
30
+
31
+ def push (self , item ):
32
+ self .stack .append (item )
33
+
34
+ def pop (self ):
35
+ if len (self .stack ) > 0 :
36
+ return self .stack .pop ()
37
+
38
+ def peek (self ):
39
+ if len (self .stack ) > 0 :
40
+ return self .stack [len (self .stack )- 1 ]
41
+ else :
42
+ return None
43
+
44
+ def __str__ (self ):
45
+ return str (self .stack )
46
+ ''' CLASS STACK() END '''
47
+
48
+ stack = list ()
49
+ # .append method to append items to the stack
50
+ stack .append (1 )
51
+ stack .append (4 )
52
+ stack .append (9 )
53
+ stack .append (16 )
54
+ print (f"Stack is { stack } " , end = "\n \n " )
55
+ stack .pop ()
56
+ print (f"Deleted Last item of Stack (LIFO) { stack } " , end = "\n \n " )
57
+
58
+ # Calling Stack() class
59
+ stack = Stack ()
60
+
61
+ stack .push (1 )
62
+ stack .push (2 )
63
+ stack .push (3 )
64
+ stack .push ('B' )
65
+
66
+ print (f"New Stack is { stack } " )
67
+ print (f"Deleted item is { stack .pop ()} " )
68
+ print (f"Seek is at { stack .peek ()} " )
69
+
70
+
71
+
72
+ #TODO: Stack continue ( https://youtu.be/kQDxmjfkIKY?t=3077 )
73
+
You can’t perform that action at this time.
0 commit comments