# Inserting Node into a Sorted Doubly Linked List

`STDIN   Function-----   --------1       t = 14       n = 51       node data values = 1, 3, 4, 7, 934795       data = 5`
`1. Empty list2. At the beginning of the list3. Somewhere at the middle of the list4. 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;`

--

--