所以这部分代码包含了我的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 :(得分: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);
}
}
}
此外:查看命名。 mylist
说......没什么。为什么不称它为numbers
或processIDs
或类似的东西?
答案 1 :(得分: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) + ".");
}
}
}
}