Wednesday, March 7, 2007

I figured out linked lists-sorta

A. Objective : Write a functioning Linked List Program

B. Result:
Source Code:
#ifndef LINKEDLISTFUN_H
#define LINKEDLISTFUN_H
#include string // the angle brackets once again missing for the purpose of the blog
using namespace std;
struct Abroad{
string country;
int id;
Abroad *next;
};
class Country{
private:
Abroad *head;
public:
void setAbroad (string, int);
void showInfo ();
Country ()
{head = NULL;}
};
#endif

#include iostream //angle brackets missing for blog
#include string // same here
#include "LinkListFun.h"

using namespace std;
int main ()
{

Country pays;
string cname1 = "France";
string cname2 = "India";
pays.setAbroad (cname1, 5);
pays.setAbroad (cname2, 8);
pays.showInfo ();

return 0;
}
void Country :: setAbroad (string CName, int id)
{
Abroad *newAbroadPtr, *nodePtr; newAbroadPtr = new Abroad;
newAbroadPtr->country = CName; newAbroadPtr->id = id;
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;
while (nodePtr) {

cout << "Country: " <<>country <<>id << endl;
nodePtr = nodePtr->next;
}
}

Output:
Country: France
ID: 5
Country: India
ID: 8

C. Comment: I finally got a functioning linked list program to work. It's rather simple and I used code from the Gaddis Book. I finally feel like I understand that the head has to point to the beginning of the list all the time and that if you want to traverse the list, you need to have another pointer. The head should intialized to NULL inside the class constructor and you need an instance of the class declared in main to access the class's functions.

No comments: