LINKED LIST Append K

my solution is not passing one test case
here is the code for append function :
public void appendLastN(int n) throws Exception {
int k=n%this.size;
if(k==0)return;
int index=(this.size-1-n)%this.size;
if(index<0)index=-index;
Node oldLast=this.getNodeAt(this.size-1);
Node toBeLast=this.getNodeAt(index);
Node NewHead=toBeLast.next;
toBeLast.next=null;
Node oldHead=this.head;
this.head=NewHead;
oldLast.next=oldHead;
}
can you please tell me where have i gone wrong

Hi Kriti, save your code on ide.codingblocks.com and share the link here.

here ma’am : https://ide.codingblocks.com/s/62858

Hi Kirti, pls notice that it is given in question that k can be > n. Pls handle that case.
If you are given k > n then the result will be this

// Input
7 3
1 2 3 4 5 6 7

// Output
5 6 7 1 2 3 4

// Input
7 9
1 2 3 4 5 6 7

// Output
6 7 1 2 3 4 5

Pls try to see the thing in this case( k > n ). After that your code will work.

Hope this helps :slight_smile:

i have made some changes but now its not giving output for one of the test case
here is my modified code :https://ide.codingblocks.com/s/65951
i have commented my append function for better understanding.plase point out my mistake in it

Hi Kirti, none of these changes were required. The main problem was in tackling the case of k>n. This will be done by simply performing the following operation:

n = n%N // Variable Names acc to ur code.

for n = 4, N = 7 < in general k < n >
n = 4%7 = 4 itself
for n = 10, N = 7 < in general k < n >
n = 10%7 = 3

in line no. 251 of your code, you just have to pass n%N instead of just n;
I hope now you understand what do we mean if k>n.

Make this slight modification and it will work then. Hope this helps :slight_smile:

thank you for your help :slightly_smiling_face:
i found my mistake my newhead was pointing towards null for some cases and yes as you have said the changes i made were not actually required :sweat_smile: