C++ Without Fear Exercise "Reverse program to print nodes in reverse alphabetical order"

Aug 19, 2012 at 8:02pm
Hello,
As you can see in the title, there is an exercise that wants me to make this example:

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
// Alpha_List.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class node {
public:
	string name;
	node *next;
	node(string input) {name = input; next = NULL;};
};

int _tmain() {
	node *root = NULL;
	node *p_node, *new_node;
	string a_name;

	while (true) {
		cout << "Enter a name ( or ENTER to exit): ";
		getline(cin, a_name);
		if (a_name.empty())
			break;
		new_node = new node(a_name);

		// If list is new or node goes at beginning,
		// then insert as root node. Otherwise,
		// search for a node to insert node AFTER.

		if (root == NULL || a_name < root->name) {
			new_node->next = root;
			root = new_node;
			}
		else {
			p_node = root;
			while (p_node->next && a_name > p_node->next->name) {
				p_node = p_node->next;
			}
			new_node->next = p_node->next;
			p_node->next = new_node;
		}
	}

p_node = root;		// Print out all nodes
while (p_node) {
	cout << p_node->name << endl;
	p_node = p_node->next;
}

	system("PAUSE");
	return 0;

}


that writes your input in alphabetical order, the other way around (reverse alphabetical order)

It says that a simple recursion can be used to write it backwards. But I can't think of any "simple" recursion to write it.

Thank you in advance.
Aug 20, 2012 at 7:35am
You mean this:
1
2
3
4
5
p_node = root;		// Print out all nodes
while (p_node) {
	cout << p_node->name << endl;
	p_node = p_node->next;
}
backward?

Yes it's really easy:
1
2
3
4
5
6
7
8
9
10
11
void print_reverse(const node *p_node)
{
	if(p_node)
	{
		print_reverse(p_node->next);
		cout << p_node->name << endl;
	}
}
...
print_reverse(root);
...
Topic archived. No new replies allowed.