[英]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.