Skip to content

Commit c7bee93

Browse files
Implement stack using array
1 parent 6cbf142 commit c7bee93

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

implement_stack_using_array.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
def create_array(initial_size):
2+
arr = []
3+
for i in range(initial_size):
4+
arr.append(0)
5+
return arr
6+
class Stack:
7+
def __init__(self, initial_size = 10):
8+
self.arr = create_array(initial_size)
9+
self.next_index = 0
10+
self.num_elements = 0
11+
def push(self, data):
12+
if self.next_index == len(self.arr):
13+
print("out of space. Increasing arr capacity")
14+
self.handle_capacity()
15+
self.arr[self.next_index] = data
16+
self.next_index += 1
17+
self.num_elements += 1
18+
def handle_capacity(self):
19+
old_arr = self.arr
20+
self.arr = [0 for _ in range (2* len(old_arr))]
21+
for index, value in enumerate(old_arr):
22+
self.arr[index] = value
23+
def size(self):
24+
return len(self.arr)
25+
def is_empty(self):
26+
return self.num_elements == 0
27+
def pop(self):
28+
if self.is_empty():
29+
self.next_index = 0
30+
return None
31+
last_element = self.arr[self.num_elements-1]
32+
self.arr[self.num_elements-1] = 0
33+
self.num_elements -= 1
34+
self.next_index -= 1
35+
return last_element
36+
37+
38+
39+
40+
stack = Stack()
41+
stack.push("a")
42+
stack.push("b")
43+
print(stack.pop())
44+
45+
print(stack.pop())
46+
print(stack.pop())
47+
48+
49+
50+

0 commit comments

Comments
 (0)