156k views
5 votes
C program, Assign negativeCntr with the number of negative values in the linked list, including the list head.

#include
#include
typedef struct IntNode_struct {
int dataVal;
struct IntNode_struct* nextNodePtr;
} IntNode;
// Constructor
void IntNode_Create(IntNode* thisNode, int dataInit, IntNode* nextLoc) {
thisNode->dataVal = dataInit;
thisNode->nextNodePtr = nextLoc;
}
/* Insert newNode after node.
Before: thisNode -- next
After: thisNode -- newNode -- next
*/
void IntNode_InsertAfter(IntNode* thisNode, IntNode* newNode) {
IntNode* tmpNext = NULL;
tmpNext = thisNode->nextNodePtr; // Remember next
thisNode->nextNodePtr = newNode; // this -- new -- ?
newNode->nextNodePtr = tmpNext; // this -- new -- next
}
// Grab location pointed by nextNodePtr
IntNode* IntNode_GetNext(IntNode* thisNode) {
return thisNode->nextNodePtr;
}
int IntNode_GetDataVal(IntNode* thisNode) {
return thisNode->dataVal;
}
int main(void) {
IntNode* headObj = NULL; // Create intNode objects
IntNode* currObj = NULL;
IntNode* lastObj = NULL;
int i; // Loop index
int negativeCntr;
negativeCntr = 0;
headObj = (IntNode*)malloc(sizeof(IntNode)); // Front of nodes list
IntNode_Create(headObj, -1, NULL);
lastObj = headObj;
for (i = 0; i < 10; ++i) { // Append 10 rand nums
currObj = (IntNode*)malloc(sizeof(IntNode));
IntNode_Create(currObj, (rand() % 21) - 10, NULL);
IntNode_InsertAfter(lastObj, currObj); // Append curr
lastObj = currObj; // Curr is the new last item
}
currObj = headObj; // Print the list
while (currObj != NULL) {
printf("%d, ", IntNode_GetDataVal(currObj));
currObj = IntNode_GetNext(currObj);
}
printf("\\");
currObj = headObj; // Count number of negative numbers
while (currObj != NULL) {
/* Your solution goes here */
currObj = IntNode_GetNext(currObj);
}
printf("Number of negatives: %d\\", negativeCntr);
return 0;
}

User SeanMC
by
6.9k points

1 Answer

3 votes

Answer:

if(currObj->GetDataVal() < 0)

{

negativeCntr++;

}

Step-by-step explanation:

This is the solution in C++ try in C see if it works (I'm more knowledgeable on C++)

You have to use the function GetDataVal() in order to receive the value attached to the currObj you are looking for. The while loop used above it goes through each node to see if it's not null, or in other words, if the memory location has a value. If the location has a value then the value itself is checked and if the value is less than 0, negativeCntr = negativeCntr + 1;

User JKirchartz
by
6.5k points