Linked List Functions Flashcards
Memorizing code for different steps of different operations for linked lists
What makes a linked list link to the next element in the list?
One of the instances is a pointer to a struct
How do we make sure that memory was allocated to the node/part of the list?
Asserting a certain condition so it prints an error message in the case where it dosen’t apply
What are the three steps to inserting a node at the head of a linked list?
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
What would be the code for something like this?
intnode_t *new_node = malloc(sizeof(intnode_t));
assert(new_node != NULL);
new_node->value = elem;
new_node->next = head;
return new_node;
What does the function push do?
Pushed a new node to the front of the linked list, insertes a node at the head of the list
What is the code to traverse through the list to the desired position using current?
// 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 do you set up a new node’s link to the next node?
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;
What would be the code to delete every other node?
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 } }
What is the code to be able to reverse a linked list (assuming that it’s already initialized)?
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;
}