简体   繁体   English

交换 LinkedList 的两个节点

[英]Swap two Nodes of LinkedList

**You have been given a singly linked list of integers along with two integers, 'i,' and 'j.' **你已经得到一个单链整数列表以及两个整数“i”和“j”。 Swap the nodes that are present at the 'i-th' and 'j-th' positions.交换出现在“第 i 个”和“第 j 个”位置的节点。

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;
        
    }

}

To make it more efficient you can remove one of the for loops.为了提高效率,您可以删除其中一个 for 循环。 first add another variable named LinkedListNode<Integer> t=head;首先添加另一个名为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. ,然后你可以先检查 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM