File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
Ch03. Basic Data Structures/Stack/stack-linked-list Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ class Node :
3+ def __init__ (self , key = None , next = None ):
4+ self .key = key
5+ self .next = next
Original file line number Diff line number Diff line change 1+ from node import Node
2+
3+ class Stack :
4+ def __init__ (self ):
5+ self .head : Node = None
6+ self .length : int = 0
7+
8+ def isEmpty (self ):
9+ return self .head is None
10+ # self.length == 0
11+
12+ def size (self ):
13+ # avoid linked list traversal
14+ return self .length
15+
16+ def peek (self ):
17+ if self .isEmpty ():
18+ raise Exception ('Stack is empty' )
19+ else :
20+ return self .head .key
21+
22+ def pop (self ):
23+ if self .isEmpty ():
24+ raise Exception ('Stack is empty' )
25+ else :
26+ retNode : Node = self .head
27+ self .head = self .head .next
28+ self .length -= 1
29+ return retNode .key
30+
31+ def push (self , item ):
32+ self .length += 1
33+ self .head = Node (item , self .head )
34+
35+
36+ s = Stack ()
37+ print (s .isEmpty ())
38+ s .push (4 )
39+ s .push ('dog' )
40+ print (s .peek ())
41+ s .push (True )
42+ print (s .size ())
43+ print (s .isEmpty ())
44+ s .push (8.4 )
45+ print (s .pop ())
46+ print (s .pop ())
47+ print (s .size ())
You can’t perform that action at this time.
0 commit comments