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
|
#include<iostream>
#include<string>
struct country_t{
std::string name;
double quantity;
};
struct Node{
std::string name;
double num;
Node* next;
};
//!! insert needs to know a list to insert into.
Node* insert(Node* head, country_t element);
int main(){
country_t arr[] = {
{"Hungary", 10},
{"Serbia", 6.95},
{"Czeh Republic", 10.65},
{"Romania", 19.41},
{"England", 55.98},
{"Austria", 8.86}
};
int n = sizeof(arr) / sizeof(arr[0]);
//!! main starts off with an empty list.
Node* head = nullptr;
for(int i = 0; i < n; i++){
head = insert(head, arr[i]);
}
return 0;
}
Node* createNode(country_t element){
Node* new_node = new Node;
if(new_node){
new_node->name = element.name;
new_node->num = element.quantity;
new_node->next = nullptr;
}
return new_node;
}
//!! pass in the current head
Node* insert(Node* head, country_t element){
Node* prev;
Node* new_node = createNode(element);
if(head == nullptr){
head = new_node;
}else if(head != nullptr){
for(Node* i = head; i->num < new_node->num; i++){
prev = i;
}
new_node->next = prev->next;
prev->next = new_node;
}
return head;
}
|