Inserting Node into a Sorted Doubly Linked List

STDIN   Function
----- --------
1 t = 1
4 n = 5
1 node data values = 1, 3, 4, 7, 9
3
4
7
9
5 data = 5
1. Empty list
2. At the beginning of the list
3. Somewhere at the middle of the list
4. At the end of the list
DoublyLinkedListNode *newNode;
newNode -> data = data;
if(head == NULL){
newNode -> prev = NULL;
newNode -> next = NULL;
return newNode;
}
if(head->data >= newNode->data){
newNode -> next = head;
head -> prev = newNode;
newNode -> prev = NULL;
head = newNode;
left->data < newNode->data && right->data >= newNode->data
current = head;
while(current->next != NULL && current->next->data < newNode->data) {
current = current->next;
}
newNode->next = current->next;
newNode->prev = current;
current->next->prev = newNode;
current->next = newNode;
current->next = newNode; //current->next now points to the newNode
current->next->prev = newNode; //current->next is the newNode, so its prev (i.e. newNode->prev) is set back to newNode which is incorrect.
DoublyLinkedListNode *newNode;
newNode->data = data;
if(head == NULL) {
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}if(head->data >= newNode->data) {
newNode->next = head;
newNode->prev = NULL;
head->prev = newNode;
head = newNode;
}
else {
DoublyLinkedListNode *current = head;
while(current->next != NULL && current->next->data < newNode->data) {
current = current->next;
}
newNode->prev = current;
newNode->next = current->next;
if(current->next != NULL) {
current->next->prev = newNode;
}
current->next = newNode;
}
return head;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store