Finding Elements in Linked List
Sep 15, 2011 at 2:05pm UTC
I'm having trouble with the 3rd if statement of my code if(select == 3). Here, if the user selects '3', then they should be able to search for students (given that students have already been inputted), via their ID. However, my code isn't doing that, and it can only search for the first student.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
#include <iostream>
#include <cstdlib>
using namespace std;
int counter = 1;
struct Node
{
char name[100];
int age;
int ID;
Node *link;
};
int main()
{
Node *start = NULL;
int select = 1;
while (select)
{
cout << "1. " << "List All Values in the List\n" ;
cout << "2. " << "Add a New Value at the End of the List\n" ;
cout << "3. " << "Search via ID\n" ;
cout << "0. " << "Exit the Program\n" ;
cin >> select;
Node *temp, *temp2;
if (select == 1)
{
//Node *temp;
temp = start;
system("cls" );
cout << "ID\tName\tAge\n" ;
while (temp != NULL)
{
cout << temp -> ID << "\t" << temp -> name << "\t" << temp -> age << endl;
temp = temp -> link;
}
}
if (select == 2)
{
//Node *temp, *temp2;
temp = new Node;
cout << "Enter Name:\n" ;
cin >> temp -> name;
cout << "Enter Age:\n" ;
cin >> temp -> age;
temp -> link = NULL;
if (start == NULL)
{
start = temp; //gives start the address of the new node
}
else
{
temp2 = start;//gives the new node the address of start
while (temp2 -> link != NULL)//while the address of temp2 is not NULL
{
temp2 = temp2 -> link;
}
temp2 -> link = temp;
}
temp -> ID = counter;
counter++;
system("cls" );
}
if (select == 3)//having trouble here, it doesn't ouput the ID and names of the students as it should
{
temp2 = start;
cout << "Enter ID of Person of Interest: " ;
int search;
cin >> search;
bool decision=1;//as of true by default
while (temp2 -> link != NULL)
{
if (search == temp2 -> ID)
{
cout << "ID\tName\n" ;
cout << temp2 -> ID << "\t" << temp2 -> name << endl;
decision = 0;
}
}
if (decision)
{
cout << "record not found\n" ;
}
}
}
return 0;
}
Any help is truly appreciated :)
Sep 15, 2011 at 2:12pm UTC
Add temp2 = temp2->link;
and replace the while condition with temp2 != NULL
And start using more meaningful variable names than "temp".
Sep 15, 2011 at 2:14pm UTC
Where would I add temp2 = temp2->link;
?
Sep 15, 2011 at 2:16pm UTC
After the if statement. Sorry, forgot to mention that part. But I suppose you could have deducted that yourself if you fully understood how a linked list works, so maybe you should review what exactly you are doing.
Sep 15, 2011 at 2:16pm UTC
oh actually, i think i got it. thanks so much. and yeah, i'll work on my naming variables :) thanks again!
Topic archived. No new replies allowed.