c - Insert an element in the middle of a linked list, in a ordered way? -
i got linked list:
typedef struct t_node { elemlist data; struct t_node *next; } node; typedef node *list; and try insert integer in ordered way (from smaller bigger numbers), seems something's not working:
status insertinorderlist(list *list, const elemlist *pelem) { node *newnode, *nodeins; newnode = getnode();//allocate memory nodeins = getnode(); //checkout getnode return newnode->data = *pelem; (nodeins = *list; nodeins != null; nodeins = nodeins->next) { if (cmpelelist(&newnode->data, &nodeins->data) != 1) { //if arg1 not > arg2 breaks loop break; } } newnode->next = nodeins; nodeins->next = newnode; return ok; } when run it tell me list empty...
i'm sure it's detail missed, can't realize what
your code several things incorrectly:
- you're allocating 2 nodes; not 1 (this isn't java or c#).
- you don't account possibility first node in list may "greater" incoming node.
- you don't wire new node in correctly.
i have absolutely no idea how comparison function works. code seems indicate returns 1 long list first value "less" second (which opposite of how comparators work. this:
- lhs < rhs : return < 0
- lhs == rhs : return 0
- lhs > rhs : return > 0
be may, retrofitted algorithm regardless.
status insertinorderlist(list *list, const elemlist *pelem) { node *newnode = getnode(); newnode->data = *pelem; while (*list && cmpelelist(&(*list)->data, pelem) != 1) list = &(*list)->next; newnode->next = *list; *list = newnode; return ok; } this assumes if list empty *list null, , allocation succeeded. tailor whatever wish. best of luck.
Comments
Post a Comment