muigai unaka
Week 4
A Last-In-First-Out data structure that is a common use of an array. Think of a stack of plates in your cupboard, new plates are added on top of the previous plates and to get a plate, you would remove the top plate
Add to a stack using .push()
let stack = [];
stack.push(3)
Remove from a stack using .pop()
let stack = []; stack.push(3); stack.push(2); stack.push(1);
stack.pop(); // removes 1, which was the last added element
A First-In-First-Out data structure that is a common use of an array. Think of a single register line at the movie theater, new people are added to the end or taken from the beginning once they have their ticket
Add to a queue using .push()
let queue = [];
queue.push(1)
Remove from a queue using .shift()
let queue = []; queue.push(1); queue.push(2);
queue.shift(); // removes 1 from the beginning
A sequence data structure, which connects elements, called nodes, through links. Nodes in a linked list are connected by pointers. Linked lists are null terminating, which means whenever the pointer to the next node is null, the list has reached the end.
When you think of a Linked List, a real world example would be a music playlist. The first song in the playlist would be the head. It connects to the next song and each song has a reference to a previous and next song. You know you've reached the end of the playlist when there is no next song.
// To create a Linked List you will need "Nodes"
// Nodes will have data and a reference to the next Node
function Node (data) {
this.data = data;
// every node starts off with their next set to null
this.next = null;
}
let head = new Node(1);
// We "link" lists by reassigning the next value of a node
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(true);
head.next.next.next.next = new Node({
fun_fact: "Linked Lists can store any data"
})
let LinkedList = head;