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?