Stacks Flashcards
Memorizing pop, peek, and push and any specifics related to the functioning of stacks
What is the philosophy of a stack?
A stack is last-in, first-out (LIFO)
What are the 3 main stack operations that we learn to implement?
1) push
2) peek
3) pop
What does the function push do?
Stores an element in a new node and inserts it at the head of the linked list O(1)
What does a pop function do?
RETURNS the element in the head node and removes that node O(1)
What does the operation peek do?
RETURNS the element in the head node without bringing any modifications to the linked list
How come pop() is a bool?
After it successfully stores the first elem and removes the first node, it returns true. It will return false if the stack is empty when pop is called
What would be the code for pop()?
_Bool pop(CU_stack_t stack, int elem) {
assert(stack != NULL && elem != NULL);
if (stack->size == 0) {
return false;
}
*elem = stack->top->element;
node_t *to_remove = stack->top;
stack->top = to_remove->next;
free(to_remove);
stack->size–;
return true;
}
How can peek() return a bool?
Retrieves the element from the top of the stack and stores the element in the location pointed to by elem and returns true. It will return false if the stack is empty when peek is called
What is an example code for peek?
_Bool peek(CU_stack_t stack, int elem) {
assert(stack != NULL && elem != NULL);
if (stack->size == 0) {
return false;
}
*elem = stack->top->element;
return true;
}