Help with error

prob: https://hack.codingblocks.com/app/contests/2022/293/problem

sol: https://ide.codingblocks.com/s/410952

I’m also not able to comprehend how this code is working without passing the head by reference

time stamp of the problem 03:08:36

Okay so first of all let me tell you why this is not working well. So what you are doing is inserting each and every node at the end of the linked list. And your breakCycle function will work for a circular linked list. So you are implementing your breakCycle function on single linked list which is not even circular, hence TLE.
Also algo seems right to me, try to submit it here as circular linked list is provided in the input just check your breakCycle function

What issue you are facing in this?

In this same video kartik bhaiya has made a function create cycle . You can implement from that too. Also if need any help do let me know.

whenever we want to change the linked list permanently we pass the head pointer by reference
but here we didn’t

oh understood but how do I know which node the last node will point to to create a cycle

You have memorised it. It’s not a fixed rule. Suppose a linked list is there and i break it’s link from 3 position by using an iterator , now in this case I haven’t used pass by address method to break it. Think linked list as block of train and next as the chain connecting two blocks. This will help you in imagining it quite well.

Iterate over a linked list, let us name it as temp. When you reach at the end of the linked list by using temp. Make temp->next point to any of the node to create a cycle. You can see this video , it will give you more clear idea. See that part where kartik bhaiya has implemented createcycle function.

yeah I watched and understood what he did but the code doesn’t seem generic sir is manually pointing temp->next to head->next->next (time stamp 2:44:43 ).

Yes , to create circular limked list. We do like this only. You could have done head->next->next->next or head->next. That’s why gave you leetcode link. Circular linked list aise he bnayi jatti hai. Kisi bhi node pr point krdo tail ko.

the code is not showing any errors but giving the wrong answer

It’s showing right output


Print it without using break cycle and you will get tle. This shows your code is working absolutely fine.

not working for this input 1 2 3 4 5 2 3 -1

Still working

but the answer is supposed to be 1 2 3 4 5

This was your circular linked list


You break the connection between 3 tail to 3
Resultant will be this only na?

yeah but I also have a prev pointer in my code at 5 and im making it point to NULL to get rid of the 2, 3

Your prev is at last 3 and your 3->next = null, so linked list is broken from there not from 5. Do dry run on your own, you will get it. Else it would b tough to understand.

oh makes sense the function is doing its job correctly so how do I remove the last two nodes, this question was a bit confusing