Monday, February 22, 2010

Recursion in Linked Lists

Around 30 mins into this video is a great explanation of recursion in linked lists:

In a nutshell, here is what the code might look like:

struct Student {
string name, address, phone;
Student *next;
};

What this allows for is the ability to enter the data for the Student structure, which then points to the next Student structure, and so forth, and so on.

Here is a revised copy of the code she uses in the video:
void PrintStudent(Student *s)
{
cout <<> name << " " <<>phone <<>
}

Student *GetNewStudent()
{
cout << "Enter name (Enter to quit):";
string name = GetLine();
if (name == "") return NULL;
Entry *newOne = new Student;

newOne->name = name; // same as *newOne.name;
// except that the arrow operator combines the dot and the //asterisk together to accomplish the same thing and //maintain order, otherwise it would need to look like this: //(*newOne).name;
cout << "Enter address:";
newOne->address = GetLine();
cout << "Enter phone:";
newOne->phone = GetLine();
newOne->next = NULL;
return newOne;
}

Student *BuildStudent()
{
Student *list = NULL;
while (true)
{
Student *newOne = GetNewEntry();
if (newOne == NULL) break;
newOne->next = list; // connects new node to next in list
list = newOne; // connects head of list to new node
}
return list;
}

int main ()
{
Student *n = GetNewStudent();
PrintStudent (n);
return 0;
}

No comments:

Post a Comment