2. 3. 2 Main Data Structures Algorithms Flashcards
Stacks
- First In Last Out (FILO) data structure, implemented as an array using single pointer (top pointer)
- The top pointer points to the element currently at the top of the stack, initialised at -1 because first position in stack is position 0
Pseudocode for size()
Returns number of elements in stack, does this by increasing top pointer by 1 (First element in position 0)
Pseudocode for isEmpty()
Checks if the stack is empty, does this by checking if the pointer is less than 0 (If its 0 there is one item in the stack)
Pseudocode for peek()
- Checks what the top pointer value is without removing the value
- First check if the stack is empty to avoid an error
- A is our array representing a stack
Pseudocode for push()
- New item to be added to stack passed as a parameter
- Top pointer is updated prior to addition so that no data is overwritten
- The new element is then inserted at the position of the top pointer
Pseudocode for pop()
- Before removing an item, a check is done to make sure the stack is not empty
- The element at the top of the pointer is recorded before being removed
- The top pointer is decremented by one before the removed item is returned
Example of a Stack
- What would the result be of the following 3-element stack?
- Keep in mind that 3 is not added to the stack because it is only a 3-element array, therefore attempting to add another item when the stack was full lead to an error
Queues
- First In First Out (FIFO) data structure, implemented as an array, make use of two pointers (front and back)
- Front points to (stores) position of first element
- Back points to (stores) position of the next available space
Pseudocode for size()
- Work out size of queue by subtracting the back pointer from the top pointer
- For example, if front is 0 and back is 5, there are 5 elements in the queue
Pseudocode for isEmpty()
When queue is empty, front and back should be the same value, check if this is the case to determine if the queue is empty
Pseudocode for peek()
Peek returns element at the front of the queue without removing it
Pseudocode for enqueue(element)
To add an element, element placed in position of back pointer, back pointer is then incremented by 1
Pseudocode for dequeue()
Items removed from queue from position of front pointer, important to check if queue is empty before doing so to avoid an error
Example of a Queue
What happens if the following operations are ran on the queue above?
Linked Lists
- Composed of nodes, each node has a pointer to the next item in the list
- Lets say a node is N, the node after than would be N.next
- The first item/element is the head, the last item/element is the tail
- Lists are searched using a linear search, sequential “next” operation till desired element found