Problem:
Given a sorted doubly linked list, insert an element into it.
Solution:
structListNode {intVal; ListNode*prev; ListNode*next;};intInsert (ListNode *head,intvalue) {ListNode*cur; ListNode*Next; for(cur = head; (next = cur->next)! = NULL; Cur =next) { if(Next->val = =value)return 0; if(Next->val >value) Break; } ListNode*newnode =NewListNode; NewNode->val =value; NewNode->next =Next; Cur->next =NewNode; if(cur! =head) NewNode->prev =cur; ElseNewNode->prev =NULL; if(Next! =NULL) Next->prev =NewNode; ElseHead->prev =NewNode; return 1;}
There are two points to note:
1. Declare a head node, where Head->prev points to the last node in the list, and Head->next points to the first node of the list.
2. The insert action is not performed when the element is inserted and the elements in the linked list are duplicated.
Reference
"C and Pointers"
Inserting a doubly linked list