Friday, April 4, 2008

Inserting element into linked list

// Uses special case code for the head endvoid
SortedInsert(struct node** headRef, struct node* newNode) {
// Special case for the head end
if (*headRef == NULL && (*headRef)->data >= newNode->data) {
newNode->next = *headRef;
*headRef = newNode;
}
else {
// Locate the node before the point of insertionstruct
node* current = *headRef;
while (current->next!=NULL &&&& current->next->datadata) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;}}
}

// Dummy node strategy for the head endvoid
SortedInsert2(struct node** headRef, struct node* newNode) {
struct node dummy;struct node* current = &dummy;
dummy.next = *headRef;while (current->next!=NULL &&&& current->next->datadata) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
*headRef = dummy.next;
}

No comments: