What is below function doing?
Note: we assume the memory for the new node has already been allocated and a pointer to that memory is being passed to this function. Also assume that the linked list will be already in sorted order?
// Special case code for the head end
void linkedListFun(struct node** headReference, struct node* newNode)
// Special case for the head end
if (*headReference == NULL || (*headReference)->data >= newNode->data)
newNode->next = *headReference;
*headReference = newNode;
// Locate the node before which the insertion is to happen!
struct node* current = *headReference;
while (current->next!=NULL && current->next->data < newNode->data)
current = current->next;
newNode->next = current->next;
current->next = newNode;
This is the logic to insert new node at the starting position of this singly linked list.
It is adding new node in the sorted (ascending) order.
This is the logic to insert new node at the ending position of this singly linked list.
It is adding new node in the sorted(descending) order.
This is the logic to add new node in the sorted (ascending) order. In the first if condition we are checking if header data is greater than supplied node data, then we are making newly inserted node as the header node. That means we are inserting in ascending data order.
Back To Top