Source of linkint.cpp


  1: // Filename: LINKINT.CPP
  2: // Purpose:  Illustrate a sequence of linked nodes.

  4: #include <iostream>
  5: #include <iomanip>
  6: using namespace std;

  8: typedef int DataType;
  9: struct  Node
 10: {
 11:     DataType data;
 12:     Node* link;
 13: };
 14: typedef Node* NodePointer;


 17: int main()
 18: {
 19:     cout << "\nThis program builds a sequence of "
 20:          << "linked nodes of integers of size 3 with "
 21:          << "\nvalues read from the keyboard and "
 22:          << "then prints out values."
 23:          << "\nEnter three values on the following "
 24:          << "line and then press ENTER: \n";

 26:     NodePointer head, current, next;

 28:     head = new Node;      // Get a first node
 29:     current = head;       // Make current point at the first node
 30:     cin >> current->data; // Read a value into the first node

 32:     next = new Node;      // Get a new node (the second one)
 33:     current->link = next; // Attach the current (first) node to the second
 34:     current = next;       // Make current point at the second node
 35:     cin >> current->data; // Read a value into the second node

 37:     next = new Node;      // Get a new node (the third one)
 38:     current->link = next; // Attach the current (second) node to the third
 39:     current = next;       // Make current point at the third node
 40:     cin >> current->data; // Read a value into the third node

 42:     current->link = NULL; // Make sure sequence is terminated properly

 44:     // Output the data value in each node
 45:     cout << endl;
 46:     current = head; // Make current point at head of sequence
 47:     while (current != NULL)  // while the end of sequence not reached
 48:     {
 49:         cout << setw(5) << current->data; // Output value pointed at by current
 50:         current = current->link;          // Move current pointer to next node
 51:     }
 52:     cout << endl << endl;

 54:     return 0;
 55: }