Stacks Flashcards

Memorizing pop, peek, and push and any specifics related to the functioning of stacks

1
Q

What is the philosophy of a stack?

A

A stack is last-in, first-out (LIFO)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the 3 main stack operations that we learn to implement?

A

1) push
2) peek
3) pop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the function push do?

A

Stores an element in a new node and inserts it at the head of the linked list O(1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does a pop function do?

A

RETURNS the element in the head node and removes that node O(1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does the operation peek do?

A

RETURNS the element in the head node without bringing any modifications to the linked list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How come pop() is a bool?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What would be the code for pop()?

A

_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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How can peek() return a bool?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is an example code for peek?

A

_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;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly