Problem with my first linked list attempt.
[EDIT] Please read my reply, as well, it has more information [EDIT]
[EDIT] Problem solved. :) Sorry noone got to help. You can read on if you wish to watch me talking to myself [EDIT]
Alright let me start out by saying this is hardly an attempt. I took the tutorials' linked list and in trying to understand it, added a thing or two. I have no idea if what I think I doing correctly is actually correct, so tell me if something is wrong.
So... a bit about the code(before I show you the code). I took the tutorial code and wrapped the statement that transverses through the list and adds new nodes and wrapped it into a for loop set to run 50 times. Each time it loops, it creates a new node and sets the value of the node to a random number from 0-50 (using rand()).
Ok, simple so far. As far as I could see, I had no problems with that. Now the next thing I did was create a function that searches the list for a specific number. Starts from the beginning, checks to see if that node is the number, if it isn't it moves until it either gets to the end or finds the number. I'm doing this wrong. For whatever reason, when it gets to the part of the function where it searches for the number, it crashes. If someone could explain why, I'd be very appreciative.
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
string searchList(int);
struct node {
int x;
node *next;
};
int main() {
node *root;
node *conductor;
srand ( time(NULL) );
root = new node;
root->next = 0;
root->x = 12;
conductor = root;
for (int y = 0; y <= 50; y++) {
if ( conductor != 0 ) {
while ( conductor->next != 0)
conductor = conductor->next;
}
conductor->next = new node;
conductor = conductor->next;
conductor->next = 0;
conductor->x = rand() % 50;
}
cout << searchList(rand() % 50);
cin.get();
return 0;
}
string searchList(int y) {
node *root;
node *conductor;
conductor = root; // I'm not sure if I'm initizalizing enough to get back
// to the beginning of the list here.
cin.get(); // Fine at this point, crashes when I continue
if ( conductor != 0 ) {
while ( conductor->next != 0 && conductor->x != y)
conductor = conductor->next;
}
if ( conductor->x == y )
return "Number was in the list"; // I know this is highly unnessasary
else // when I could just make a void
return "Number was not in the list"; // function and cout this, but I
// figured "what the hell".