I'm new to C, so be patient with me if you see some really newbie error in my code!
As part of the homework, I need to create an ordered list to store some data. What I have done so far is to create a structure that will represent each node of the list (firstNode is a global variable that points to the first node of the list):
typedef struct Node {
struct Node *next;
int id;
int value;
}Node;
Node *firstNode = NULL;
After that, I created a function that inserts a new node into the list, checking the values of the nodes. Nodes with lower values should be in front of others. So I did this:
void addNewNode(int nodeId, int nodeValue) {
Node *newNode = (Node*) malloc(sizeof(Node));
Node *temp, *tempPrev;
newNode->id = nodeId;
newNode->value = nodeValue;
if(firstNode == NULL) {
newNode->next = firstNode;
firstNode = newNode;
}
temp = firstNode;
tempPrev = NULL;
while(temp->value < newNode->value) {
tempPrev = temp;
temp = temp->next;
}
if(tempPrev == NULL) {
newNode->next = firstNode;
firstNode = newNode;
}
else {
tempPrev->next = newNode;
newNode->next = temp;
}
}
The problem with the above code is that sometimes the program crashes, but I can not find the error!
, , , , , ( ). ? !
opaque