2017-09-12 37 views
-1

所以这是我的代码中包含我的LinkedList的一部分。我如何在我的数字集中找到匹配项。如何匹配LinkedList中的索引值

LinkedList <Integer> mylist = new LinkedList<>(); 
for(int i : 1; i<=5; i++){ 
System.out.println("Process " + i + has :); 
int numINPUT = scan.nextint(); 
mylist.add(numINPUT); 
} 

我所需的输出是:

Process 1 has : 3 
Process 2 has : 4 
Process 3 has : 1 
Process 4 has : 5 
Process 5 has : 2 
Matched : Process 1 and Process 3. 
+0

这些数值来自哪里? –

+0

请提供一些更多的说明。 –

+0

我很好奇。你的代码如何编译? –

回答

0

您只需比较所有列表项目对。如果一个项目的索引等于另一个项目的值,反之亦然,您可以匹配。请记住,Java指数从0开始,您的索引以1开头。

public static void main(String[] args) { 

    Scanner scan = new Scanner(System.in); 

    LinkedList <Integer> mylist = new LinkedList<>(); 
    for(int i = 1; i<=5; i++){ 
     System.out.print("Process " + i + " has: "); 
     int numINPUT = scan.nextInt(); 
     mylist.add(numINPUT); 
    } 

    for(int i = 0; i < mylist.size(); i++) { 
     for(int j = i + 1; j < mylist.size(); j++) { 
      int value1 = mylist.get(i); 
      int value2 = mylist.get(j); 
      if(value1 == (j + 1) && value2 == (i + 1)) { 
       System.out.println("Matched : Process " + (i + 1) + " and Process " + (j + 1) + "."); 
      } 
     } 
    } 
} 
2

蛮力事情可能是这样的:

for (int i=0; i<mylist.size(); i++) { 
    int pointingToIndex = mylist.get(i); 
    if (pointingToIndex > 0 && pointingToIndex < mylist.size) { 
    int pointedTo = mylist.get(pointingToIndex); 
    if (pointedTo == i) { 
     System.out.println("match for index: " + i + " and " + pointingToIndex); 
    } 
    } 
} 
  • 您只需重复您的列表;并为每个指标您是否对指数是另一种有效的索引
  • 如果是这样,你取的,其他指标值,然后检查匹配
  • 你可能需要一些额外的“标记“以避免打印重复(我认为我的解决方案将打印1-3,然后在3-1之后)
  • 是的,这并不完全打印你所要求的 - 但应该给你足够的前进和完成你自己的功课

此外:看看你的命名mylist说......没什么。为什么不叫它numbers或者processIDs或类似的东西?