Skip to content

Instantly share code, notes, and snippets.

@fabianbaechli
Created April 22, 2025 14:04
Show Gist options
  • Select an option

  • Save fabianbaechli/baa4260e1963c270a8b85dbd9911dcaf to your computer and use it in GitHub Desktop.

Select an option

Save fabianbaechli/baa4260e1963c270a8b85dbd9911dcaf to your computer and use it in GitHub Desktop.
// Implementation without a guard:
int main() {
struct Node* root = newNode(0);
struct Node* newBeginning = newNode(-1);
newBeginning -> next = root;
root = newBeginning;
}
// Implementation using a guard:
int main() {
struct Node* root = newNode(NULL);
struct Node* firstRealElement = newNode(0);
root -> next = firstRealElement;
struct Node* newBeginning = newNode(-1);
newBeginning->next = firstRealElement;
root->next = newBeginning;
// WE DON'T HAVE TO REASSIGN ROOT
}
// Implementation using Double Pointer
void insertAtBeginning(struct Node** head, int val) {
struct Node* new = newNode(val);
new->next = *head;
*head = new;
}
int main() {
struct Node* head = NULL; // empty list
insertAtBeginning(&head, 10); // head = 10 -> NULL
insertAtBeginning(&head, 20); // head = 20 -> 10 -> NULL
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment