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
|
#include <iostream>
#include <string>
using namespace std;
struct Node
{
string name;
double gpa;
Node *link;
};
typedef Node* NodePtr;
void addToFront(NodePtr& head, string s, double num);
void printList(NodePtr head);
void addAfter(NodePtr afterMe, string s, double num);
void removeAfter(NodePtr afterMe);
NodePtr findMax(NodePtr head);
int main()
{
Node *head = NULL;
string name;
double gpa = 0;
addToFront(head, name, gpa);
name = "James";
gpa = 3.5;
addToFront(head, name, gpa);
name = "John";
gpa = 3;
addToFront(head, name, gpa);
name = "Peter";
gpa = 3.8;
addToFront(head, name, gpa);
name = "Mark";
gpa = 2.9;
addToFront(head, name, gpa);
//by using addToFront function, build the following linked list
//HEAD--> (Mark, 2.9) --> (Peter, 3.8) --> (John, 3.0) --> (James, 3.5) -->NULL
cout << "The original linked list has: \n";
printList(head);
name = "Sam";
gpa = 3.7;
NodePtr temp1 = head->link->link;
addAfter(temp1, name, gpa);
cout << "After inserting node Sam: \n";
printList(head);
NodePtr temp2 = head;
removeAfter(temp2);
//Insert a node(Sam, 3.7) between John and James. Display list to confirm it.
cout << "After removing node Peter: \n";
printList(head);
removeAfter(head);
//Delete Peter node, and display list to confirm it.
NodePtr max = findMax(head);
cout << "The max gpa: \n" << max->name << " & " << max->gpa << endl;
return 0;
}
void printList(NodePtr head)
{
for (Node *n = head; n != NULL; n = n->link)
{
cout << n->name << " & " << n->gpa << " --> ";
if (n->link == NULL)
cout << "NULL\n\n";
}
}
void addAfter(NodePtr afterMe, string s, double num)
{
Node * temp = new Node;
temp->name = s;
temp->gpa = num;
temp->link = afterMe->link;
afterMe->link = temp;
}
void addToFront(NodePtr& head, string s, double num)
{
Node* temp = new Node;
temp->name = s;
temp->gpa = num;
temp->link = head;
head = temp;
}
void removeAfter(NodePtr afterMe)
{
Node * temp = afterMe->link;
afterMe->link = temp->link;
delete temp;
}
NodePtr findMax(NodePtr head)
{
NodePtr max;
double maxGPA = 0;
max = NULL;
for (Node *n = head; n != NULL; n = n->link)
{
if (n->gpa > maxGPA)
{
maxGPA = n->gpa;
max = n;
}
}
return max;
}
|