Reputation: 11
**You have been given a singly linked list of integers along with two integers, 'i,' and 'j.' Swap the nodes that are present at the 'i-th' and 'j-th' positions.
My code is as below, can you suggest an efficient alternate way?**
public static LinkedListNode<Integer> swapNodes(LinkedListNode<Integer> head, int i, int j) {
//Your code goes here
LinkedListNode<Integer> temp=head;
LinkedListNode<Integer> temp1=head;
LinkedListNode<Integer> tempo=new LinkedListNode<Integer>(0);
int beg=0, end=0;
for(int x=0;x<i;x++)
{
temp=temp.next;
}
for(int y=0;y<j;y++)
{
temp1=temp1.next;
}
tempo.data= temp.data;
temp.data= temp1.data;
temp1.data=tempo.data;
return head;
}
}
Upvotes: 0
Views: 451
Reputation: 790
To make it more efficient you can remove one of the for loops. first add another variable named LinkedListNode<Integer> t=head;
, then you can first check between i and j and see which one is bigger and do a for loop for that.
LinkedListNode<Integer> t=head;
int counter = (i > j) ? i : j;
for(int x=0;x<counter;x++)
{
t = t.next;
if(counter == i-1){
temp=t.next;
}
if(counter == j-1){
temp1=t.next;
}
}
Upvotes: 1