C: Creating an ordered list by checking 2 values

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!

, , , , , ( ). ? !

+5
5

, while , temp NULL. , node , , , temp ( temp NULL), node! , :

while(temp!=NULL && temp->value>newNode->value)
{
    ....
}

, while :

while(temp!=NULL && (temp->value<newNode->value || (temp->value==newNode->value && temp->id<newNode->id))
{
    ....
}

, if, , firstNode NULL, . NULL, while if-statement while.

, C: -)

+3

1.

if(firstNode == NULL) {
        newNode->next = firstNode;
        firstNode = newNode;
        return; // done with inserting the first node...need not continue.
    }

2.

// ensure temp is not null only then access its value.
while(temp && (temp->value < nodeId->value)) {
        tempPrev = temp;
        temp = temp->next;
    }
+1

-, nodeID → . NodeID - int, .

0

, . , , , , (, ). unit test , . , , , , . unit test , , .

0

, (, , , ; , , , - ). "print", . , , . ( , ) , , malloc . , , malloc NULL, .

Node *newNode = (Node*) malloc(sizeof(Node)); 
if(newNode == NULL)
{
  printf("Out of Memory!");
  return;
}
0
source

All Articles