-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_node.py
More file actions
49 lines (36 loc) · 1.05 KB
/
stack_node.py
File metadata and controls
49 lines (36 loc) · 1.05 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
# Python programe for linked list implementation
# Class to represent a node
class StackNode:
# Constructor to initialize a node
def __init__(self, data):
self.data = data
self.next = None
class Stack:
# Constractor to initialize the root of linked list
def __init__(self):
self.root = None
def is_empty(self):
return True if self.root is None else False
def push(self, data):
new_node = StackNode(data)
new_node.next = self.root
self.root = new_node
print("%d pushed to stack" %(data))
def pop(self):
if self.is_empty():
return float("-inf")
temp = self.root
self.root = self.root.next
popped = temp.data
return popped
def peek(self):
if self.is_empty():
return float("-inf")
return self.root.data
# Driver program to test above class
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print("%d popped from stack." %stack.pop())
print("Top element is %d " %stack.peek())