1/30
Looks like no tags are added yet.
Stack
is a linear data structure that follows the LIFO (Last In, First Out) principle. The last element added to the stack is the first one to be removed.
A stack of books
The Undo button in Word
The Back button in a web browser
stack of bracelets
Real-world examples of stacks:
TOP
A stack has only ONE accessible end, called what?
BASE or BOTTOM
The other end of a stack is called what?
it is closed - you cannot add or remove elements there directly.
push(x)
Adds element x to the top of the stack
pop()
Removes and returns the top element
peek() / top()
Returns the top element WITHOUT removing it
isEmpty()
Checks whether the stack has zero elements
isFull()
Checks whether the stack has reached its maximum capacity (array-based only)
size()
returns the size of the stack.
Array-Based Stack
uses a fixed-size array plus a variable (commonly called 'top') that keeps track of the index of the top element.
Linked-List-Based Stack
stack uses a singly linked list, where the HEAD of the list always represents the TOP of the stack.
Queues
is a linear data structure that follows the FIFO (First In, First Out) principle. The first element added to the queue is the first one to be removed.
rear
Position of the last entry in the queue, that is, the one most recently added
front
Position of the entry in a queue ready to be served, that is, the first entry that will be removed from the queue
head
other term for front
tail
other term for rear
Size
refers to the current number of elements in the queue.
Capacity
refers to the maximum number of elements the queue can hold.
People lining up
Customer service call centers
Cars waiting in a single-lane toll booth.
Real-world examples of queues:
FIFO Principle
states that the first element added to the Queue will be the first one to be removed or processed.
enqueue(x)
Adds element x to the rear of the queue
dequeue()
Removes and returns the front element
front() / peek()
Returns the front element WITHOUT removing it
Returns the front element WITHOUT
Checks whether the queue has zero elements
isFull()
Checks whether the queue has reached its maximum capacity (array-based only)
Linear (Simple) Queue
Circular Queue
Priority Queue
Double-Ended Queue (Deque)
Types of Queues
Linear (Simple) Queue
an array-based queue, once the rear reaches the last index, no more elements can be added - even if front slots were freed by dequeues - unless elements are shifted.
Circular Queue
Solves the wasted-space problem of a linear queue by connecting the rear back to the front. When the rear reaches the end of the array, it wraps around to index 0 if that slot is free.
Priority Queue
Elements are removed based on PRIORITY rather than arrival order.
Double-Ended Queue (Deque)
Allows insertion and removal from BOTH ends - front and rear. A deque can behave like a stack, a queue, or both at once.