I am currently working on a linked list program that asks the user to enter numbers into a linked list, and then asks the user to input a number to search for in the list. I am having some problems with the searchNodes function and I was wondering if someone could help me out. The problem is that when I(the user) sends a number to the function it doesn't output the numbers position. Here is what I have so far:
// This program allows the user to enter data into a linked list
// then calls a function that searches the linked list for a number
// that the user wants to find. If it is in linked the list the function
// then returns a number indicating its position in the list. If it isn't found
// then the function just returns a 0.
#include <iostream>
usingnamespace std;
struct ListNode {
float value;
ListNode *next;
};
ListNode *head = NULL;
float insertNode(float num);
float searchNodes(float num);
int main()
{
int num, value;
char answer;
do {
cout << "Please enter a value to put in the list --> ";
cin >> num;
insertNode(num);
cout << endl;
cout << "Would you like to put another value into your list? ";
cin >> answer;
} while(toupper(answer)=='Y');
do {
cout << "Please enter the value you would like to search for in the list--> ";
cin >> value;
searchNodes(num);
cout << endl;
cout << "Would you like to search for another value? ";
cin >> answer;
} while(toupper(answer)=='Y');
}
float insertNode(float num)
{
struct ListNode *newNode, *nodePtr = head, *prevNodePtr = NULL;
newNode = new ListNode;
if(newNode == NULL) {
cout << "Error allocating memory for new list member!\n";
return 1;
}
newNode->value = num;
newNode->next = NULL;
if(head==NULL) {
cout << "List was empty - " << newNode->value;
cout << " is part of list's first node.\n";
head = newNode;
}
else {
while((nodePtr != NULL) && (nodePtr->value < num)) {
prevNodePtr = nodePtr;
nodePtr = nodePtr->next;
}
if(prevNodePtr==NULL) {
newNode->next = head;
head = newNode;
}
else {
newNode->next = nodePtr;
prevNodePtr->next = newNode;
}
}
return 0;
}
float searchNodes(float num)
{
struct ListNode *nodePtr = head, *prevNodePtr = NULL;
int count = 0;
while((nodePtr != NULL) && (nodePtr->value != num)) {
++count;
prevNodePtr = nodePtr;
nodePtr = nodePtr->next;
}
if (nodePtr->value = num) {
cout << "Your value was in the list, at position " << count << ".\n";
}
else {
count = 0;
cout << "The value you have entered was not in the list!\n";
return 0;
}
}