B. Result: This first program is the addition of a new node and another field in the linked list:
#ifndef MARCH20_H
#define MARCH20_H
#include <string>
using namespace std;
struct Abroad
{
string country;
int countryCode;
string currencyType;
Abroad *next;
};
class Country
{
private:
Abroad *head;
public:
void setAbroad (string, int, string);
void showInfo ();
Country ()
{head = NULL;}
};
#endif
#include <iostream>
#include <iomanip>
#include <string>
#include "march20.h"
using namespace std;
int main ()
{
Country pays;
string cname1 = "France ";
string cname2 = "India ";
string cname3 = "Denmark";
string FrenchCurrency = "Euro";
string IndianCurrency = "Rupee";
string DanishCurrency = "Danish Krone";
pays.setAbroad (cname1, 33, FrenchCurrency);
pays.setAbroad (cname2, 91, IndianCurrency);
pays.setAbroad (cname3, 45, DanishCurrency);
pays.showInfo ();
return 0;
}
void Country :: setAbroad (string CName, int cCode, string currencyT)
{
Abroad *newAbroadPtr, *nodePtr;
newAbroadPtr = new Abroad;
newAbroadPtr->country = CName;
newAbroadPtr->countryCode = cCode;
newAbroadPtr->currencyType = currencyT;
newAbroadPtr->next = NULL;
if (!head)
head = newAbroadPtr;
else
{
nodePtr = head;
while (nodePtr->next)
{
nodePtr = nodePtr->next;
}
nodePtr->next = newAbroadPtr;
}
}
void Country :: showInfo ()
{
Abroad *nodePtr;
nodePtr = head;
cout <<"----------------------------------------\n";
cout <<" Country " <<>country;
cout <<>countryCode;
cout <<>currencyType <
nodeptr="nodePtr-">next;
}
}
----------------------------------------
Country Calling Code Currency
----------------------------------------
France 33 Euro
India 91 Rupee
Denmark 45 Danish Krone
The following link is to my .cpp file where I tried sorting the linked list.
My .cpp file
C. Comment: I was never able to sort the list. When I tried doing so, the last node did not show up in the output. I would really like to figure out how to sort the linked list. I will try working on it further but at this point I am stuck.
2 comments:
Quite clearly, its a pain to sort a linked list. So your approach i.e. keep the list in sorted order while adding is the best one. The only missing element here is that when you are inserting an element, say 7 between lets say 5 and 9, you need to set 7's next to 9. What you have is 7 stored in a newNode and 7's next is currently pointing to null. So before you set 5's next to 7, you need to first set 7's next to 5's next (i.e. 9). So you'd end up adding the line newAbroadPtr->next = nodePtr->next; before the last line in the else block of your setAbroad. I hope that helps.
Abhishek
He beat me to it. :)
Post a Comment