#LinkedList Insertion problem

66 messages · Page 1 of 1 (latest)

thick mulch
#

So, I decided to practice a bit of DS and stuff, and I have a problem.

void insert(LinkedList** head, LinkedList* current, int pos)
{
    std::cout << "Node count " << count_nodes(*head) << std::endl;
    if (pos > count_nodes(*head) || pos < 0)
    {
        std::cout << "Out of bounds! position is bigger than node count" << std::endl;
        return;
    }
    if (pos == 0)
    {
        current->next = (*head);
        *head = current;
    }
    else
    {
        for (int idx = 0; idx < pos - 1; idx++)
        {
            if ((*head)->next != nullptr)
            {
                *head = (*head)->next;
            }
        }
        current->next = (*head)->next;
        (*head)->next = current;
    }
}
int main()
{
    LinkedList* head = nullptr;
    LinkedList* current = nullptr;
    int n;
    std::cout << "Enter the max value of of random element" << std::endl;
    std::cin >> n;
    std::random_device os_seed;
    const unsigned int seed = os_seed();
    std::mt19937 generator(seed);
    std::uniform_int_distribution<unsigned int> distribute(1, n);
    for (int idx = 0; idx < 10; idx++)
    {
        current = create_node(distribute(generator));
        insert(&head, current, idx);
    }
}

I'm trying to create a bunch of linkedlists using a for loop and then iteratively inserting them one after another, what happens is that after the second iteration, it doesn't link the second and third node properly so it enters the out of bounds check. I tried debugging but I see the nodes be created in the debug window (see screenshot 2) so I"m confused as to why -- do pardon I barely used linkedlists at this point so it's problably something very trivial.
Any help?

uncut flumeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

jaunty thunder
thick mulch
#

so that I can insert in the beginning
say that I wanted to add an element at index 0

#

as well

jaunty thunder
#

yeah but why not just pass a head*?

#

doesn't seem to offer any benefit here besides worse syntax

thick mulch
#

Well, because then if I were to add at index 0 it wouldn't create an element before it.

#

since, from my understanding you need two pointers to redirect one pointer to another so that you can overwrite the first element
say 0 1 2
if I wanted to add 3 at the beginning I'd need a double ptr no?

jaunty thunder
#

oh wait your reasigning the head pointer, just pass the original pointer as a reference

#

much better syntax and clearer intent

thick mulch
jaunty thunder
#
void insert(LinkedList*& head, LinkedList* current, int pos)
{
    std::cout << "Node count " << count_nodes(head) << std::endl;
    if (pos > count_nodes(head) || pos < 0)
    {
        std::cout << "Out of bounds! position is bigger than node count" << std::endl;
        return;
    }
    if (pos == 0)
    {
        current->next = head;
        head = current;
    }
    else
    {
        for (int idx = 0; idx < pos - 1; idx++)
        {
            if (head->next != nullptr)
            {
                head = head->next;
            }
        }
        current->next = head->next;
        head->next = current;
    }
}
int main()
{
    LinkedList* head = nullptr;
    LinkedList* current = nullptr;
    int n;
    std::cout << "Enter the max value of of random element" << std::endl;
    std::cin >> n;
    std::random_device os_seed;
    const unsigned int seed = os_seed();
    std::mt19937 generator(seed);
    std::uniform_int_distribution<unsigned int> distribute(1, n);
    for (int idx = 0; idx < 10; idx++)
    {
        current = create_node(distribute(generator));
        insert(head, current, idx);
    }
}
#

should work as well then

thick mulch
#

oh right, the reference

jaunty thunder
#

sorry it's early morning see what you want to do now :)

thick mulch
#

Thank you for clearing it up a bit, but the issue is still prelevant

#

the syntax definitely is better than the overlayered pointers.

jaunty thunder
#

yeah right

thick mulch
#

Usually when you want to write such a function and DS, is it better to seperate the idea of adding in the beginning or would you normally just write an insert at with a position index so that you have more control and less functions to handle?

jaunty thunder
#

hmmm I think this is fine what you have now (besides the bug ofc)

#
       for (int idx = 0; idx < pos - 1; idx++)
        {
            if (head->next != nullptr)
            {
                head = head->next;
            }
        }
        current->next = head->next;
        head->next = current;

hmmmm this shouldn't modify the head no?

#

cause if you insert at say pos 3 the head should remain the same

#

at host the head->next value is changed but the actual head pointer shouldn't be reasigned

thick mulch
#
        for (int idx = 0; idx < pos - 1; idx++)
        {
            if (head->next != nullptr)
            {
                *head = *head->next;
            }
        }
        current->next = head->next;    
    }
}```
#

so you're saying that the ptr in the loop shouldn't be reassigned?

jaunty thunder
#

most likely, you propably want to keep your head pointer the same and only do any relinking

thick mulch
#

But then how would I move to the next element in the list? since the idea is to insert at the end
and you can achive that by moving the ptr from the first element to the last one

jaunty thunder
#
LinkedList* temp = head;
 for (int idx = 0; idx < pos - 1; idx++)
        {
            if (temp->next != nullptr)
            {
                temp = temp->next;
            }
        }
        current->next = temp->next;
        temp->next = current;
#

eg this

#

it leaves the actual head value on the outside unchanged but fixes up any links

thick mulch
#

It works now.

#

Thank you, it seems my understanding of pointers is still very much at an average level and there is much more to do.

jaunty thunder
#

biiiiiig

thick mulch
#

And much more to learn.

jaunty thunder
#

so the issue was indeed the reasigning of the head ptr

#

you know why that is an issue?

thick mulch
#

could it be because

#

once we reassign the ptr value

#

to the next head

#

it counts from the next head onwards

jaunty thunder
#

yeah

thick mulch
#

so that when it comes to the check (it sees) that

#

the count would go

jaunty thunder
#

essentially, in your previous code if you where to say a node at pos 3 your head is nor permanently up 2 nodes and the nodes before are lost

thick mulch
#

its counting 2 node since I skip over the first one

#

because I"ve moved the ptr once correct?

#

bah

jaunty thunder
thick mulch
#

and here because it worked fine for the first two I expected all was well, well. That's my problem for not paying close attention to the code count nodes function and expecting it to work when my other logic isn't sound

jaunty thunder
#
[1][2][3][4][5]
 ^head
 
insert at 3
[1][2][6][4][5]
    ^head
#

this was kinda what was happening

thick mulch
#

yeah

#

instead of starting 0 1 2 3

#

it goes

#

1 2 3

#

and misses the first one

jaunty thunder
#

yeah, and 0 is lost

thick mulch
#

okay well if anything it's a lesson to take home is to learn how to write pointers carefully and not be careless with the code.

#

🤣

#

Thanks again, I would have been stuck for hours if it wasn't for you.

jaunty thunder
#

bno worries :)

thick mulch
#

Such a trivial yet pivotal mistake. :/

uncut flumeBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity