[英]Swap two Nodes of LinkedList
**你已经得到一个单链整数列表以及两个整数“i”和“j”。 交换出现在“第 i 个”和“第 j 个”位置的节点。
我的代码如下,你能建议一个有效的替代方法吗?**
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;
}
}
为了提高效率,您可以删除其中一个 for 循环。 首先添加另一个名为LinkedListNode<Integer> t=head;
,然后你可以先检查 i 和 j 之间,看看哪个更大,然后为此做一个 for 循环。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.