LINKED LIST-K APPEND runtime error problem

only one case passed and other three cases showing runtime error.
code link - https://ide.codingblocks.com/s/104263

Hello @Ajaypandey,

The following portion of your code is causing run time error as you are trying to access a memory location that has not been allocated:
while(k–) {
fast = fast->next ;
}

This happening for the testcases where K>=N (Read the question properly)
example:
7
1 2 2 1 8 5 6
7

Dry run your code to understand this better.
Try to develop a logic that can withstand these testcases also.

Hope this would help.
If you still face problem, feel free to ask.
Give a like, if you are satisfied.

i tried doing this : if(k>=x) then return head instead of temp , that means print the linked list as it is , but now it is printing same linked list for all cases (k>=x or k<x) , can u pls edit my code ??

This logic would work correct for k=n.
But, you don’t have to print the entire linked list from start in case of k>n.
If k=n+1, the last element would become the first element as in the case of n=1;.
similary, for k=n+2 you have to do what you were doing in case of n=2;

Oh yes, you can take k%n. then apply your previous logic on the result of modulo.
This way for k=n, k%n=0, then it will automatically print the entire linked list as it is, if you’ll use your previous logic.

BTW, send your code, if it does not work after modifications.

i have got your point , but it still sowing runtime error , this is the code link - https://ide.codingblocks.com/s/105117

This is happening because of the variable x, you are using in the function kthelement()

It must be the size of array you have entered before.
But, you declared that in another function createlinkedlist().
Thus, x is local variable to this function.
So, how can you expect x to have the same value in another function.

Solution: declare and take input for x in the main function and then pass it both the functions.

Hope, this would help.
Give a like, if you are satisfied.

1 Like

tysm !!! all the test cases have been passed . :wink:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.