// PROGRAM ID: CreateList / Code to create an anchored singly linked list // REMARKS: This module contains a C++ function, CreateList, that creates // an "anchored singly-linked list" using values from standard input. // The items in the list should be in ascending (sorted) order. #include #include "CreateList.h" using namespace std; void insertNode( tNodePtr& head, double num ); void CreateList( tNodePtr& head ) // OUT { double item; // Input value to be inserted into linked list head = nullptr; for (int k=0; k<10; ++k) { cin >> item; insertNode(head, item); } return; } //************************************************** // The insertNode function inserts a node (inorder)* // with num copied to its value member. * //************************************************** void insertNode( tNodePtr& head, double num ) // INOUT IN { tNodePtr newNode; // A new node tNodePtr nodePtr; // To traverse the list tNodePtr previousNode = nullptr; // The previous node // Allocate a new node and store num there. newNode = new ListNode; newNode->value = num; // If there are no nodes in the list // make newNode the first node if (head==nullptr) { head = newNode; newNode->next = nullptr; } else // Otherwise, insert newNode { // Position nodePtr at the head of list. nodePtr = head; // Initialize previousNode to nullptr. previousNode = nullptr; // Skip all nodes whose value is less than num. while (nodePtr != nullptr && nodePtr->value < num) { previousNode = nodePtr; nodePtr = nodePtr->next; } // If the new node is to be the 1st in the list, // insert it before all other nodes. if (previousNode == nullptr) { head = newNode; newNode->next = nodePtr; } else // Otherwise insert after the previous node. { previousNode->next = newNode; newNode->next = nodePtr; } } return; }