Adding and sorting a linked list in C
Posted
by
user1202963
on Stack Overflow
See other posts from Stack Overflow
or by user1202963
Published on 2012-04-06T23:25:29Z
Indexed on
2012/04/06
23:29 UTC
Read the original article
Hit count: 172
In my assignment, I have to write a function that takes as arguments a pointer to a "LNode" structure and an integer argument. Then, I have to not only add that integer into the linked list, but also put place it so that the list is in proper ascending order. I've tried several various attempts at this, and this is my code as of posting.
LNode* AddItem(LNode *headPtr, int newItem)
{
auto LNode *ptr = headPtr;
ptr = malloc(sizeof(LNode));
if (headPtr == NULL)
{
ptr->value = newItem;
ptr->next = headPtr;
return ptr;
}
else
{
while (headPtr->value > newItem || ptr->next != NULL)
{
printf("While\n"); // This is simply to let me know how many times the loop runs
headPtr = headPtr->next;
}
ptr->value = newItem;
ptr->next = headPtr;
return ptr;
}
} // end of "AddItem"
When I run it, and try to insert say a 5 and then a 3, the 5 gets inserted, but then the while loop runs once and I get a segmentation fault.
Also I cannot change the arguments as it's part of a skeletal code for this project. Thanks to anyone who can help.
If it helps this is what the structure looks like
typedef struct LNode
{
int value;
struct LNode *next;
} LNode;
© Stack Overflow or respective owner