forked from super30admin/PreCourse-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise_2.py
More file actions
58 lines (45 loc) · 1.6 KB
/
Exercise_2.py
File metadata and controls
58 lines (45 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Time Complexity : Push - O(1), Pop - O(1)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no
# Your code here along with comments explaining your approach
# 1. Use a linked list where 'top' always points to the most recently pushed node.
# 2. For push: create a new node, point its next to current top, and update top.
# 3. For pop: return the data from top and move top to top.next.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, data):
# Create new node and add it at the top of stack
new_node = Node(data)
new_node.next = self.top
self.top = new_node
def pop(self):
# If the stack is empty, return None
if not self.top:
return None
popped_value = self.top.data
self.top = self.top.next # Move top to next node
return popped_value
# ------------------- Example Interaction Code (as you provided) -------------------
a_stack = Stack()
while True:
print('push <value>')
print('pop')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
a_stack.push(int(do[1]))
elif operation == 'pop':
popped = a_stack.pop()
if popped is None:
print('Stack is empty.')
else:
print('Popped value: ', int(popped))
elif operation == 'quit':
break