Quick actions

cmd+k|ctrl+k

Navigation

Languages

Data Structures: Stacks With Linked Lists

Snippet info

Language

Python

Visibility

public

Author

rakeshbhatia87

Created

2023-01-02T21:00:09.004615Z

Updated

2023-01-04T07:14:48.970678Z

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class Stack:
    def __init__(self):
        self.top = None
        self.bottom = None
        self.length = 0
        
    def peek(self):
        return self.printTop()
  
    def push(self, value):
        newNode = Node(value)
        if self.length == 0:
            self.top = newNode
            self.bottom = newNode
        else:
            newNode.next = self.top
            self.top = newNode
        self.length += 1
        return self.printStack()

    def pop(self):
        '''if self.length == 0:
            self.top = None
            self.bottom = None
            self.length = 0'''
        if not self.top:
            return None
        if self.top == self.bottom:
            self.bottom = None
        self.top = self.top.next
        self.length -= 1
        return self.printStack()
    
    def printTop(self):
        print(self.top.value)
    
    def printStack(self):
        currentNode = self.top
        #values = []
        while currentNode:
            #values.append(currentNode.value)
            print(currentNode.value, end=' -> ')
            currentNode = currentNode.next
        #print(values)
        print()
    
    #isEmpty

myStack = Stack()

#Discord
#Udemy
#google

myStack.push("Discord")
myStack.push("Udemy")
myStack.push("google")
#myStack.pop()
myStack.peek()
INFO