Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
4. The next problem addresses adding a new element to a doubly-linked list.
Remember that
i) the elements of the list are to kept in ascending numerical order.
ii) your answers must address issues of a) adding to an empty list, b) adding at the start of the list, c) adding to the end of the list, as well as d) adding somewhere in the middle of an existing list.
Posted

1 solution

/* Adding to an empty chain*/
doubleChainCell* addInOrder(doubleChainCell *header, int data) {
doubleChainCell *addee = new(NULL, data, NULL);
if (header == NULL) {
header = addee;
return header;
}

/* Adding at the start of the chain */
if (data < header->data) {
addee->next = header;
header = addee;
return header;
}

/* Adding at the end of the chain */
doubleChainCell *pt = header, *previous = NULL;
while ((pt != NULL) && (data > pt->data)) {
previous = pt;
pt = pt->next;
}
previous->next = addee;
addee->previous = previous;
addee->next = pt;
if (pt != NULL) {

pt->previous = addee;
}
return header;
}
 
Share this answer
 
Comments
jack545 24-Feb-12 0:34am    
what does this mean

if (data < header->data) {
addee->next = header;
header = addee;
return header;
krumia 24-Feb-12 3:31am    
Could you please format your code using a pre tag?
nv3 24-Feb-12 6:48am    
Is this a home work assignement? If yes, then we don't do you any good to provide you with a cheater. If no, what are you trying to accomplish? Please explain, so that we can give you more than just a piece of source code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900