Created
April 22, 2025 14:23
-
-
Save fabianbaechli/f0f9d534e6f9abf9992d5e6856b9dd46 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// can also be implemented using functions which return the altered head of the list | |
struct node { | |
int val; | |
struct node* next; | |
}; | |
struct node** init() { | |
struct node** l = malloc(sizeof(struct node*)); | |
*l = NULL; | |
return p; | |
} | |
int getFirst(struct node** l) { | |
// If *l is NULL, the list is empty | |
if (*l == NULL) return -1; | |
else return (*l)->val; | |
} | |
void insert(struct node** l, int x) { | |
struct node* p; | |
struct node* q; | |
// insertion at first place needs special handling | |
if (*l == NULL || (*l)->val > x) { | |
p = malloc(sizeof(struct node)); | |
p->val = x; | |
p->next = *l; | |
*l = p; | |
} else { | |
p = *l; | |
while (p->next != NULL && p->next->val < x) { p = p->next; } | |
q = malloc(sizeof(struct node)); | |
q->val = x; | |
q->next = p->next; | |
p->next = q; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment