Apr 23, 2022 at 10:00am UTC
Hi! I have a working linked list code so far, but I am curious if I can use Node* head or something like that in the parameters instead of Node** head. My tasks says to use a function with this parameter in the function: adat* head, but I just can't make my program work that way.
Thanks for the answers in advance!
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
#include <iostream>
using namespace std;
struct adat{
double num;
adat* next;
};
void insert(adat** head, double num);
void print(adat* head);
int main() {
adat* head = NULL;
insert(&head, 3);
insert(&head, 2);
insert(&head, 1);
print(head);
return 0;
}
adat* new_node(double num){
adat* n_node = new adat;
if (n_node){
n_node->num = num;
n_node->next = nullptr ;
}else {
std::cout << "Unable to create node!\n" ;
}
return n_node;
}
void insert(adat** head, double num){
adat* new_n = new_node(num);
adat* curr;
if (*head == nullptr || (*head)->num >= new_n->num){
new_n->next = *head;
*head = new_n;
}else {
curr = *head;
while (curr->next != nullptr && curr->next->num < new_n->num){
curr = curr->next;
}
new_n->next = curr->next;
curr->next = new_n;
}
}
void print(adat* head){
while (head){
std::cout<< head->num << ' ' ;
head = head->next;
}
std::cout << '\n' ;
}
Last edited on Apr 23, 2022 at 10:15am UTC
Apr 23, 2022 at 7:45pm UTC
I was thinking about this version: void insert(Padat& root, double num), so you were correct :) In this version, do I change the pointers and such this way..? Sorry if I'm wrong, I'm kinda dumb to pointers ^^'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
void insert(adat head, double num){
adat* new_n = new_node(num);
adat* curr;
if (head == nullptr || head.num >= new_n->num){
new_n->next = &head;
head = new_n;
}else {
curr = head;
while (curr.next != nullptr && curr.next->num < new_n->num){
curr = curr->next;
}
new_n->next = curr.next;
curr.next = new_n;
}
}
Last edited on Apr 23, 2022 at 7:49pm UTC
Apr 24, 2022 at 12:13pm UTC
The void insert(Padat& root, double num)
is same
as void insert(adat*& root, double num)
and totally different
from void insert(adat root, double num)
Last edited on Apr 24, 2022 at 12:14pm UTC