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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
|
// Bob Zambanini - Monday, March 14, 2011 - lab5_2.cpp
//
// This program - delayed from lab on Monday, February 28, 2011 -
// studies 3 basic operations of a linked list: inserting,
// traversing, and deleting.
//
#include <iostream>
using namespace std;
const short unsigned int NUMVALS = 10;
struct ListNode {
double value;
ListNode* next;
};
ListNode* head = NULL;
template <class T>
bool insertNode(T num)
{
ListNode* newNode;
ListNode* nodePtr = head;
ListNode* prevNodePtr = NULL;
newNode = new ListNode;
if(newNode == NULL) {
cout << "Error allocating memory for new list member!\n";
return 1;
}
newNode->value = num;
newNode->next = NULL;
if(head==NULL) { // check if list is currently empty
cout << "List is currently empty - " << newNode->value;
cout << " is part of the list's first node!\n";
head = newNode;
}
else {
while(nodePtr != NULL && nodePtr->value<num) {
prevNodePtr = nodePtr; // advance prevNodePtr up to nodePtr
nodePtr = nodePtr->next; // advance nodePtr by 1 node
}
if(prevNodePtr == NULL) {// at beginning of list
newNode->next = head;
head = newNode;
}
else {
prevNodePtr->next = newNode;
newNode->next = nodePtr;
}
}
return 0;
}
template <class V>
V appendNode(V num)
{
ListNode* newNode;
ListNode* nodePtr = head;
ListNode* prevNodePtr = NULL;
newNode = new ListNode;
if(newNode == NULL) {
cout << "Error allocating memory for new list member!\n";
return 1;
}
newNode->value = num;
newNode->next = NULL;
if(head==NULL)
{
cout<<"list was empty -" <<newNode->value;
cout<<" is part of list's first node.\n";
head = newNode;
}
else
{
while (nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
return 0;
}
void displayList(void);
int main(void)
{
double dumVals[NUMVALS] = {10.5, 131.5, 120.5, 317, 126,
1392, -99.9, 365, 1111.334, 1};
short unsigned int i;
for(i=0; i<NUMVALS; i++) { // insert the array values into the linked list
if(insertNode(dumVals[i])) {
cout << "Error in function insertNode!\n";
cout << "Program will halt!\n";
exit(1);
}
}
displayList();
cout << endl << endl;
appendNode(123);
displayList();
cout << endl << endl;
displayList();
cout << endl << endl;
}
void displayList(void)
// This function displays our linked list!
{
ListNode* nodePtr = head;
if(head == NULL) {
cout << "List is currently empty!\n";
}
else {
while (nodePtr != NULL) {
cout << nodePtr->value << endl;
nodePtr = nodePtr->next;
}
}
}
|