List Based Collections
1-1 Linked Lists
stores a reference to the next element in the list
next component is storing the memory address of the next element
Linked List & Array
Main distinction?
: each element stores different information
Pros & Cons
Pros
: pretty easy to insert & delete elements
Cons
: need to be careful not to lose references when adding or removing elements
Linked List in Python
There isn't a built-in data structure in Python that books like a linked list.
But, it's easy to make classes that represent data structures in Python!
ex) Linked List
Stack
: List-based data structure
-> has a bit of a different flair than arrays & linked lists
How it works?
You keep putting elements on top
You have easy access to remove or look at the top element
When to use?
when you only care about the most recent elements
the order in which you see & save elements actually matters
Push & Pop
Push
: when you add an element to a stack
-> O(1)
Pop
: when you taken an element off of the stack
-> O(1)
=> All you need here is to look at the top element of the stack!
Stack == L.I.F.O
: Last In First Out Structure
Stack in Python
pop()
is a given functionappend()
is equivalent to a push function
Make your own code instead of using append()
since it traverses the whole list, taking O(n)
-> it will take a lot faster if we push/pop from the first element in a linked list!
ex)
+
alternative delete_first()
method
ex)
Queues
Queues == F.I.F.O
: First In First Out Structure
Head & Tail
Head
: the first (the oldest) element in the queue
Tail
: the last element (the newest) in element in the queue
Enqueue & Dequeue
Enqueue
: add an element to the tail
Dequeue
: remove the head element
Peek
: look at the head element, but not removing it
Deque
: a queue that goes both ways
-> you can enqueue & dequeue from either end
-> kind of a generalized version of both stacks & queues since you could represent either of them with it!
Priority Queue
assign each element a numerical priority when you insert it into the queue
remove the element with the highest priority when you dequeue
-> if the elements have the same priority, the oldest element is the one that gets dequeue first
Queues in Python
ex)
Last updated