//C++: linked list
#include <iostream>
#include <cstdlib> // for system("PAUSE")
#include <iomanip>
using namespace std;
struct nodeType {
int info;
nodeType* link;
}; // 不要忘了分号
nodeType* buidListForward();
nodeType* buildListBackward();
int main() {
nodeType* head;
nodeType* current;
head = buildListBackward();
current = head;
cout << "list = ";
int count = 0;
while(current != NULL) {
cout << setw(5) << current -> info;
count++;
if(count % 10 == 0)
cout << endl;
current = current -> link;
}
system("PAUSE");
return 0;
}
//build a linked list forward
nodeType* buildListForward() {
nodeType *first, *last, *newNode;
int num;
cout << "Enter a list of integers ending with -999"
<< endl;
cin >> num;
first = NULL;
while (num != -999) {
newNode = new nodeType;
newNode -> info = num;
newNode -> link = NULL;
//insert the new node
if(first == NULL) {
first = newNode;
last = newNode;
}
else {
newNode -> link = first;
first = newNode;
}
cin >> num;
}
return first;
}
//build a list backward
nodeType* buildListBackward() {
nodeType *first, *newNode;
int num;
cout << "Enter a list of integers ending with -999"
<< endl;
cin >> num;
first = NULL;
while (num != -999) {
newNode = new nodeType;
newNode -> info = num;
newNode -> link = first;
first = newNode;
cin >> num;
}
return first;
}
运行结果如下: