Ll-k elements challenge

What is the Error in my Code?

Please share your code so that I can help you out. Paste your code to ide.codingblocks.com, save it and then share the link here.

this.getAt(i+k-1)=a;
this.getAt(i)=this.getAt(i+k-1);

You cannot modify values like this, your function getAt() returns you the value of a node, so you cannot assign a variable to a value. For example if this.getAt(i+k-1) returns 5, you are doing 5=a, which is an invalid assignment. Only a = 5 would be a valid statement.

Could you please check this out now.

Did you save your code after making changes to it? Because when I opened it, it is the same code as before

Sorry. Just forgot. Please Check now.

What you are doing is, your are just changing the values of local variables a, b and c. But you need to modify the actual linked list. So you need to change the data of the nodes, so use the function getNodeAt() and change the node.data. Also, whenever you call a function that throws an exception inside another function, you need to add ‘throws exception’ to your function as well. Check your for loop increment as well.

public void reverse(int k) throws Exception{

for(int i=0; i<this.size(); i=i+k){

   Node a = getNodeAt(i);
   Node b = getNodeAt(i+k-1);
      
      int c = a.data;
      a.data = b.data;
      b.data = c;

    } 

}

It is still showing the same errors.

I have sent the corrected code above. You haven’t added ‘throws exception’ to your function. And you have changed the type of a but you are still using the getAt() function instead of getNodeAt(). Please refer to the code I have shared above

Could you please elaborate on the difference between the getat and the getnodeat Functions.

Still shows run time error.

For the same Code after adding throws exception to the function.

The getAt() function returns the value of a node, whereas the getNodeAt() function returns a node of the linkedlist. Your logic will not work correctly for different values of k like k=4 or k=5 etc, because you are only swapping the first and last elements of linkedlist of size k. Try to modify your logic so that it works for all cases.
For example, 10 5
5 6 1 9 2 8 4 7 90 12
it will give wrong answer for this case. Try thinking about possible test cases and running them on your code before you submit.
For the runtime error, did you change the increment in the for loop? It should be i=i+k instead of i=i+k-1

I did change the increament of the Loop.

What do you mean by value of anode? Do you mean the data of a node?

Also why are yoiu saying that the logic is failing? I don’t find it failing.