//Program: Make a ListNode and simple linked list class. Test the linked list class by adding varous numbers to the list and then test for membership.\
//then include a search function that returns the position of x on the list, if not found return -1.
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <cstring>
#include <fstream>
#include <cctype>
usingnamespace std;
class LinkedList
{
protected:
struct ListNode
{
double value;
ListNode *next;
ListNode(double value1, ListNode *next1) //constructor
{
value = value1;
next = next1;
}
};
ListNode *head;
public:
void add(double x);
bool isMember(double x);
int search(double x);
void displayList();
};
int main()
{
LinkedList list;
double x; // user input to search
// adding numbers to list
list.add(1.2);
list.add(5.5);
list.add(6.5);
list.add(9.9);
list.add(2);
list.add(5);
list.add(7);
list.add(24);
cout << "Enter a number to search if it is in the list: ";
cin >> x;
cout << "\n\nSearching...\n\n";
// search for the number in the list
int i = list.search(x);
if (i != -1) { cout << "Number is found at position " << i << endl; }
elseif (i == -1) { cout << "Number was not found" << endl; }
// display list to user
cout << "Only these numbers are in the list: ";
list.displayList();
cout << endl << endl;
system("pause");
}
// This fnc puts a new node at the beginning of the list
void LinkedList::add(double x)
{
head = new ListNode(x, head);
}
bool LinkedList::isMember(double x)
{
ListNode *nodepointer = head; // start at the head of the list
if (nodepointer->value != NULL)
{
if (nodepointer->value == x)
{
returntrue;
}
nodepointer = nodepointer->next;
}
returnfalse;
}
int LinkedList::search(double x)
{
ListNode *nodepointer = head;
int i = 1; // initialized value for true
if (nodepointer->value != NULL)
{
if (nodepointer->value == x)
{
return i;
}
nodepointer = nodepointer->next; // move to the next node
i++;
}
return -1; // if x is not found
}
void LinkedList::displayList()
{
ListNode *nodepointer = head; // start at the head of the list
while (nodepointer)
{
cout << nodepointer->value << " "; //print current node
nodepointer = nodepointer->next; //moves to the next node
}
}
Okay, a few things:
1) You should define a default constructor for your class that initializes head to a null pointer:
30 31 32 33
public:
LinkedList(): head(nullptr) {} // Or use 0 or NULL if you don't have a C++11 compiler
void add(double x);
// ...
Right now, head seems to be getting initialized to some garbage value, which would explain the crash you're getting in displayList (because the last node points to a garbage value, not null).
2) Line 95 should just be while (nodepointer).
That way, you'll loop through all of the elements (or at least until you find the element you're looking for).