Linked List Functions Flashcards

Memorizing code for different steps of different operations for linked lists

1
Q

What makes a linked list link to the next element in the list?

A

One of the instances is a pointer to a struct

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

How do we make sure that memory was allocated to the node/part of the list?

A

Asserting a certain condition so it prints an error message in the case where it dosen’t apply

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

What are the three steps to inserting a node at the head of a linked list?

A

1) Allocating a new node and initializing the content of the new element
2) Have the new node point to the old head node
3) Have the head pointer updated to point to the new node

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

What would be the code for something like this?

A

intnode_t *new_node = malloc(sizeof(intnode_t));
assert(new_node != NULL);
new_node->value = elem;
new_node->next = head;
return new_node;

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

What does the function push do?

A

Pushed a new node to the front of the linked list, insertes a node at the head of the list

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

What is the code to traverse through the list to the desired position using current?

A

// Traverse to the node before the desired index
intnode_t *current = head;
int pos = 0;

while (current != NULL && pos < index - 1) {
    current = current->next;
    pos++;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you set up a new node’s link to the next node?

A

intnode_t *new_node = malloc(sizeof(intnode_t));
assert(new_node != NULL);
new_node->value = elem;
new_node->next = current->next;
current->next = new_node;

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

What would be the code to delete every other node?

A

void every_other(intnode_t *head) {
// Handle cases where the list is empty or has only one node
if (head == NULL || head->next == NULL) {
return;
}

intnode_t *current = head;

// Traverse the list and remove every other node
while (current != NULL && current->next != NULL) {
    intnode_t *node_to_delete = current->next;
    current->next = node_to_delete->next;  // Skip the node to delete
    free(node_to_delete);                  // Deallocate the removed node
    current = current->next;               // Move to the next remaining node
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the code to be able to reverse a linked list (assuming that it’s already initialized)?

A

node_t* reverse(node_t* head) {
if (head == NULL || head->next == NULL) {
return head;
}
node_t* newhead = NULL, *curr;
while (head != NULL) {
curr = head;
head = head->next;
curr->next = newhead;
newhead = curr;
}
return newhead;
}

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