Data Structures: Stacks With Linked Lists

Run Settings
LanguagePython
Language Version
Run Command
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()
class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.items = [] def peek(self): return self.printTop() def push(self, value): newNode = Node(value) self.items.append(newNode) self.top = self.items[-1] self.bottom = self.items[0] return self.printStack() def pop(self): if len(self.items) == 0: return None self.items.pop() if len(self.items) != 0: self.top = self.items[-1] self.bottom = self.items[0] return self.printStack() def printTop(self): print(self.top.value) def printStack(self): for item in self.items: print(item.value, end=' -> ') print() #isEmpty myStack = Stack() #Discord #Udemy #google myStack.push("Discord") myStack.push("Udemy") myStack.push("google") #myStack.pop() myStack.peek() myStack.pop() myStack.peek() myStack.printStack()
Editor Settings
Theme
Key bindings
Full width
Lines