/* listprog.cpp - Demo program to illustrate linked lists, uses a struct. Sample Run: This program finds sum or product of a variable number of integers. Enter as many integers > 0 as you would like followed by the value -1. The numbers are: 3 5 7 9 -1 Just entered Fcn. displayList... 9 7 5 3 Please select the number of one of these options: 1. Sum the numbers in the list 2. Multiply the numbers in the list 3. Exit the program. Your choice: 1 Answer is: 24 */ #include #include using namespace std; struct Node { int data; Node *nextPtr; }; void displayList( Node *head) { Node *tempPtr = head; // Used to traverse list without destroying head cout << "\n List contains: "; while( tempPtr != NULL) { cout << tempPtr->data << " "; tempPtr = tempPtr->nextPtr; } cout << "\n\n"; } long processNumbers( Node *head) { Node *tempPtr = head; long result = 0; while (tempPtr != NULL) { result += tempPtr->data; tempPtr = tempPtr->nextPtr; // Advance to next list member } return result; } // First figure out the rest of the program before attempting to understand // how reversing the list works. Node *reversing( Node *head) { Node *tempPtr; if (head->nextPtr == NULL) { return head; } else { // head->nextPtr != NULL tempPtr = reversing( head->nextPtr); head->nextPtr->nextPtr = head; // reverse link return tempPtr; } } main() { int number = 0; // Used to store numbers read in Node *head = NULL; // head of linked list Node *tempPtr; // Temporary node pointer used in reversing list int menuChoice; // Menu choice cout << "This program finds sum or product of a variable number \n"; cout << " of integers. Enter as many integers > 0 as you would like \n"; cout << " followed by the value -1.\n\n"; cout << "The numbers are: "; while ( number != -1) { cin >> number; if (number != -1) { tempPtr = new Node; // Insert at head of list tempPtr->data = number; tempPtr->nextPtr = head; head = tempPtr; } } displayList( head); while (true) { cout << "Please select the number of one of these options: \n"; cout << " 1. Sum the numbers in the list\n"; cout << " 2. Reverse the list.\n"; cout << " 3. Exit the program.\n"; cout << "Your choice: "; cin >> menuChoice; switch ( menuChoice) { case 1: // Sum numbers in list cout << "Answer is: " << processNumbers( head) << "\n"; break; case 2: // Reverse the list cout << "Before reversing, the list looks like: "; displayList( head); tempPtr = head; // keep track of original list head head = reversing( head); // Reverse list tempPtr->nextPtr = NULL; // set old head node pointer to point to NULL cout << "AFTER reversing, the list looks like: "; displayList( head); break; case 3: // Exit the program exit( 0); break; } // pause output display } return 0; }