【发布时间】:2015-03-19 18:22:14
【问题描述】:
我在比较两个链表时遇到问题,我有 2 个用于参数的列表 list1 包含 {1,2,3,4,5} 和 list2 包含 {1,3,4,5,6}
我没有使用linkedlistnodes 作为开始,这就是我在这里提出问题的原因,我确实尝试切换到笔记,但我的许多其他工作必须重新编写才能使其工作,我真的不想做。
到目前为止,这是我的代码,我正在尝试使用 2 个循环来循环和比较每个值。问题是它没有按我的预期工作,因为我认为它不会在继续之前将list1 的第一个值与list2 中的所有值进行比较。它难倒了我如何让这个工作,或者我是否以正确的方式去做。
bool c = false;
foreach (int s in list1) {
foreach (int t in list2)
if (s == t) {
c = true;
//The console write line in this part of the code is for testing
Console.WriteLine("Both Lists Match {0}, {1}", s, t);
break;
} else {
c = false;
//The console write line in this part of the code is for testing
Console.WriteLine("Not a Match {0}, {1}", s, t);
}
}
if (c == true) {
Console.WriteLine("Both Lists Match");
} else {
Console.WriteLine("Not a Match");
}
【问题讨论】:
-
您知道它们在开始时已排序吗?您是否只需要确定它们是否相等?如果不相等,是否要所有差异(在 a 中找到不是 b,在 b 中找到不是 a)?
-
我按照我生成它的方式做,但如果有办法比较它,我会更赞成。
-
你可以使用 LINQ 吗?
list1.SequenceEqual(list2)应该会给你正确的答案... -
您想确定这些列表的哪些内容?任何一个中的任何元素是否等于另一个列表中相应索引的值?
-
你应该看看stackoverflow.com/questions/12795882/…,看看它是否对你的情况有帮助。
标签: c# list linked-list compare