how can i resolve run error in this?
K append Linked List
@minal.251298
it written that k can be greater than size of lInked list in that case you have to take mode with n.
https://ide.codingblocks.com/s/211452, it is showing run error in one of the test cases, can you please look into this.?
@minal.251298
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
LinkedList list = new LinkedList ();
Scanner sc = new Scanner (System.in);
int n=sc.nextInt();
for(int k=0;k<n;k++)
{
list.addLast(sc.nextInt());
}
int k=sc.nextInt();
list.Kappend(k);
}
}
class LinkedList
{
private class Node
{
int data;
Node next;
}
private Node head;
private Node tail;
private int size;
public void display()
{
Node temp=head;
while(temp!=null)
{
System.out.print(temp.data+" ");
temp=temp.next;
}
}
public void addLast(int item)
{
Node nn= new Node();
nn.data=item;
nn.next=null;
if(size>=1)
{
this.tail.next=nn;
}
if(this.size==0)
{
this.head=nn;
this.tail=nn;
this.size++;
}
else
{
this.tail=nn;
this.size++;
}
}
private Node getNodeAt(int index) throws Exception
{
if(this.size==0)
{
throw new Exception("LL is empty");
}
if(index<0||index>=this.size)
{
throw new Exception("invalid index");
}
Node temp=head;
for(int i=1;i<=index;i++)
{
temp=temp.next;
}
return temp;
}
public void Kappend(int index) throws Exception
{
if(index>this.size)
{
index=index%this.size;
}
if(this.size!=index){
Node curr=getNodeAt(this.size-index);
Node prev=getNodeAt(this.size-index-1);
prev.next=null;
Node temp=curr;
while(temp.next!=null)
{
temp=temp.next;
}
temp.next=this.head;
head=curr;
}
Node temps=head;
while(temps!=null)
{
System.out.print(temps.data+" ");
temps=temps.next;
}
}
}
here is modified code,
you did not handle the case when n=0 or n=size.
updated code can be found here: https://ide.codingblocks.com/s/211500
please rate and resolve it if satisfied…
thanks
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.