I'm preparing for an interview soon, and I've written the following linked list implementation from scratch.
This is all self-taught, and I'm still working on my C. I feel that the implementation is correct (if someone catches a corner case though, that would be great!), and I'm looking for feedback on best C practices.
For example: Is the spacing excessive? Are 1-line control flow statements okay? Is the constructor implementation idiomatic?
Header file:
#ifndef Interview_Prep_SLL_h
#define Interview_Prep_SLL_h
typedef struct SLLNode
{
int val;
struct SLLNode* next;
} SLLNode;
SLLNode* new_SLLNode(int val);
SLLNode* SLLappend(SLLNode* head, int val);
SLLNode* SLLinsert(SLLNode* head, int val, int ind);
SLLNode* SLLdelete(SLLNode* head, int val);
SLLNode* SLLreverse(SLLNode* head);
void SLLprint(SLLNode* head);
#endif
Source file:
// constructor
SLLNode* new_SLLNode(int val)
{
SLLNode* head = malloc(sizeof(SLLNode));
head->val = val;
head->next = NULL;
return head;
}
// add node to end
SLLNode* SLLappend(SLLNode* head, int val)
{
if (head == NULL) return new_SLLNode(val);
SLLNode* curr = head;
while (curr->next != NULL) curr = curr->next;
curr->next = new_SLLNode(val);
return head;
}
// insert node at index (position) ind
SLLNode* SLLinsert(SLLNode* head, int val, int ind)
{
if (head == NULL && ind > 0) return head;
if (head == NULL && ind == 0) return new_SLLNode(val);
SLLNode* curr = head;
int count = 0;
while (curr != NULL && count < ind - 1)
{
curr = curr->next;
count++;
}
if (curr == NULL) return head;
SLLNode* temp = curr->next;
SLLNode* new = new_SLLNode(val);
curr->next = new;
new->next = temp;
return head;
}
SLLNode* SLLdelete(SLLNode* head, int val)
{
if (head == NULL) return head;
if (head->val == val) return head->next;
SLLNode* curr = head;
while (curr->next != NULL && curr->next->val != val) curr = curr->next;
if (curr->next == NULL) return head;
SLLNode* temp = curr->next;
curr->next = curr->next->next;
free(temp);
return head;
}
SLLNode* SLLreverse(SLLNode* head)
{
if (head == NULL) return head;
if (head->next == NULL) return head;
SLLNode* curr = head;
SLLNode* next = curr->next;
SLLNode* nextnext = next->next;
while (true)
{
if (curr == head) curr->next = NULL;
next->next = curr;
curr = next;
next = nextnext;
if (nextnext == NULL) return curr;
nextnext = nextnext->next;
}
}
// print values of nodes separated by spaces
void SLLprint(SLLNode* head)
{
while (head != NULL)
{
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}