Uses a data structure called Last In First Out (LIFO)
push(data)
: Operation that adds an element to the top indexappend()
for Python works the same way for Python listspop()
: Operation that deletes the top elementpeek()
: Returns the top elementisEmpty()
: Returns if the stack is empty or notUsing Linked Lists to create functions
For Linked Lists, the top element is at self.head.
def push(self, value):
# Create a new Node
newHead = Node(value)
# Point the new Node to the current head
newHead.next = self.head
# Change the head to the new Node
self.head = newHead
A new head is assigned to the next Node and the head is deleted.
def pop(self):
# Return none when the Stack is empty
if self.is_empty():
return None
# Save the current head
deleteNode = self.head
# Change the head to the next Node
self.head = deleteNode.next
return deleteNode
Shows the top data, or the head in this case.
def peek(self):
if self.is_empty():
return None
return self.head.data
Returns if the list is empty. The head would be empty in this case.
def is_empty(self):
return self.head is None
Uses a data structure called First In First Out (FIFO)
enqueue(data)
: Adds data to the last indexdequeue()
: Deletes data of the first indexpeek()
: Returns the first elementisEmpty()
: Determines if the queue is empty or notTo create this with Linked Lists, a head and tail is needed.
Adds new Node to the end (tail).
def enqueue(self, value):
newNode = Node(value)
# If the Queue is empty:
if self.is_empty():
self.head = newNode
self.tail = newNode
return
# Declare the new Node as the new tail
self.tail.next = newNode
self.tail = newNode
Deletes first Node (head).
def dequeue(self):
if self.is_empty():
return None
# Deleted head to return
deleteHead = self.head
# Change head
newHead = self.head.next
self.head = newHead
return deleteHead.data
Returns first Node (head).
def peek(self):
if self.is_empty():
return None
return self.head.data
Returns if the Queue is empty.
def is_empty(self):
return self.head is None