File tree 2 files changed +59
-13
lines changed
2 files changed +59
-13
lines changed Original file line number Diff line number Diff line change @@ -123,16 +123,3 @@ def remove(self, index):
123
123
self .length -= 1
124
124
return temp
125
125
return None
126
-
127
-
128
- dll = DoublyLinkedList (0 )
129
- dll .append (1 )
130
- dll .append (2 )
131
- dll .append (3 )
132
- dll .append (4 )
133
- dll .append (5 )
134
- dll .append (6 )
135
- dll .append (7 )
136
- dll .append (8 )
137
- dll .append (9 )
138
- dll .print_list ()
Original file line number Diff line number Diff line change
1
+ '''
2
+ Overview:
3
+ Stacks are like a stack of books.
4
+ Add an item onto the stack - Push
5
+ You can only reach the last item pushed
6
+ Removing last added item - Pop
7
+ LIFO - Last In First Out
8
+
9
+ Benefits:
10
+ O(1) to Push/Pop
11
+
12
+ Examples:
13
+ Browser History (Back Button)
14
+ Recursion
15
+
16
+ Implementation:
17
+ List
18
+ Linked List
19
+ Stack should point down so popping/pushing the top value is O(1)
20
+ without needing to find the second last node
21
+ '''
22
+
23
+
24
+ class Node :
25
+ def __init__ (self , value ):
26
+ self .value = value
27
+ self .next = None
28
+
29
+
30
+ class Stack :
31
+ def __init__ (self , value ):
32
+ new_node = Node (value )
33
+ self .top = new_node
34
+ self .height = 1
35
+
36
+ def print_stack (self ):
37
+ temp = self .top
38
+ while temp is not None :
39
+ print (temp .value )
40
+ temp = temp .next
41
+
42
+ def push (self , value ):
43
+ # O(1)
44
+ new_node = Node (value )
45
+ if self .top is None :
46
+ self .top = new_node
47
+ else :
48
+ new_node .next = self .top
49
+ self .top = new_node
50
+ self .height += 1
51
+
52
+ def pop (self ):
53
+ if self .top is None :
54
+ return None
55
+ temp = self .top
56
+ self .top = self .top .next
57
+ temp .next = None
58
+ self .height -= 1
59
+ return temp
You can’t perform that action at this time.
0 commit comments