Skip to content

Instantly share code, notes, and snippets.

@ayulockin
Created August 8, 2019 15:49
Show Gist options
  • Select an option

  • Save ayulockin/4d9f7386c3baded2528c95b66ee16f44 to your computer and use it in GitHub Desktop.

Select an option

Save ayulockin/4d9f7386c3baded2528c95b66ee16f44 to your computer and use it in GitHub Desktop.
Stack Implementation Using Linked List
class LinkedStack:
def __init__(self):
self._head = None
self._size = 0
class _node:
__slots__ = '_element', '_nextP'
def __init__(self, element, nextP):
self._element = element
self._nextP = nextP
def isEmpty(self):
return self._size == 0
def push(self, element):
self._head = self._node(element, self._head)
self._size += 1
def top(self):
if self.isEmpty():
raise Exception("Stack is empty")
return self._head._element
def pop(self):
if self.isEmpty():
raise Exception("Stack is empty")
ans = self._head._element
self._head = self._head._nextP
self._size -= 1
return ans
S = LinkedStack()
S.push(10)
S.push(20)
S.push(30)
S.push(40)
S.push(50)
## Traversal
head = S._head
while head!=None:
print(head._element)
head = head._nextP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment