I needed to write code that would alphabetize a linked list of structures, as well as define an insert and delete method for the list. What I currently have won't compile, although a few lines can easily be commented out to make it run.
//Adeeb Khadem
//3-12-2012
//Creates a linked list, then deletes and inserts nodes.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
usingnamespace std;
struct whitePage //Definition for structure.
{
string lastName;
string firstName;
string address;
string telephone;
whitePage *next_page;
};
whitePage *makeNode() //Prompts user to create a new whitePage structure
{
whitePage *pt = new whitePage;
cout << "Please enter a... "<<endl;
cout << "\n Last Name: ";
cin >> pt -> lastName;
cout << "\n FirstName: ";
cin >> pt -> firstName;
cin.ignore(20,'\n');
cout << "\n Address: ";
getline (cin, pt -> address);
cout << "\n Telephone Number: ";
cin >> pt -> telephone;
return pt;
}
void *insertNode(whitePage *head, whitePage *current){ //Recieves a head node and a new node to be inserted, then inserts the new node alphabetically by last name.
whitePage *temp;
*temp = *head;
while(temp -> next_page!= NULL) //Traverses the list until it reaches the end.
{
if (current < temp -> next_page){ //Checks to see if the item is alphabetically less. (A is less than B) If so, it inserts the new node.
*current -> next_page = *temp -> next_page;
*temp -> next_page = *current;
}
else *temp = *temp -> next_page;
}
current -> next_page = NULL;
}
void deleteNode(whitePage *head, string firstName, string lastName){ //Recieves a head node and a name to be deleted, then searches the list for the name and deletes it.
whitePage *temp;
*temp = *head;
while(temp -> next_page != NULL)
{
if(temp -> lastName == lastName && temp -> firstName == firstName){
*temp->next_page = *temp->next_page->next_page;
}
}
}
int main() //Instantiates makeNode() 10 times, followed by insertNode() and deleteNode() a few times
{
for (int i = 0; i< 10; i++){
cout<<"Creating node number "<<i+1<<"."<<endl<<endl;
whitePage *head = new whitePage;
if (i == 0){
whitePage *head = makeNode();
continue;
}
whitePage *temp = makeNode();
insertNode(head, temp);
cout<<endl;
}
return 1;
}
I've more or less got it done, but I'm having issues with two parts, the insertNode method, and the deleteNode method.
If someone could give me a push in the right direction, I would really appreciate it. I'm pretty sure that I need to mess with the pointers and references of the structures, (which I attempted) but to be honest, I come from Java so that's all a bit hazy to me. If someone could show me how to do insert, I'm sure I could use that as a springboard to finish delete.