[英]How to search an element in a Linked List? (c#)
我得到了这组代码,我需要在 while 循环上方和 While 循环中用一些代码填充它。 我看过一些文档,但我所看到的只是使用两个 arguments 的搜索方法,而这个只有一个。 我已经在while循环中写了这部分,但我注意到这是否正确。 如何完成此代码以搜索作为参数给出的值?
注意:这不是我要求你为我做的家庭作业,而是我们拥有的为数不多的学习资源之一,如果你能完成它,它会让我更好地掌握。
当我现在运行此代码时,我收到此错误消息:类型“Tests.Node”不包含“value”的定义,并且找不到“Tests.Node”类型的扩展方法“value”。 您是否缺少程序集参考?
{
public class Node<T> where T : IComparable
{
public T Value { get; }
public Node<T> Next { get; set; }
public Node(T value, Node<T> next)
{
this.Value = value;
this.Next = next;
}
}
public class LinkedList<T> where T : IComparable
{
public Node<T> start;
public LinkedList()
{
start = null;
}
public LinkedList(Node<T> node)
{
start = node;
}
public Node<T> Search(T value)
{
[here is code needed]
while (start != null)
if(start.value.CompareTo(value) == 0){
return start;
}
start = start.next;
}
}
public class Program {
public static void Main(string[] args){
var list =
new LinkedList<int>(
new Node<int>(
5, new Node<int>(
7, new Node<int>(
21, new Node<int>(
30, null)
)
)
)
);
var a = 21;
var fr = list.Search(a);
}
}
}
您非常接近正确的解决方案。 首先,您需要修复编译器错误 - 更改value
和next
的Value
和Next
,因为如何调用Node
class 上的属性。
接下来,您需要添加大括号,以便while
块将执行赋值start = start.Next;
(目前只有if
语句在 while 内,所以你会以无限循环结束)
接下来你需要修复 return - 添加return null;
在while
块之后 - 如果没有找到任何内容,您将返回值(也没有它,代码将无法编译)。
最后,您需要解决在搜索期间更改列表的问题(您正在使用start = start.Next
修改LinkedList
class 的start
字段。接下来,您不应该这样做),引入一个临时变量(我将其命名为curr
) ,为其分配start
值并在您的 while 循环中使用它:
public Node<T> Search(T value)
{
var curr = start;
while (curr != null)
{
if (curr.Value.CompareTo(value) == 0)
{
return curr;
}
curr = curr.Next;
}
return null;
}
我建议实现IEnumerable<Node<T>>
接口
public class Node<T> : IEnumerable<Node<T>> where T : IComparable {
public IEnumerator<Node<T>> GetEnumerator() {
for (Node<T> item = this; item != null; item = item.Next)
yield return item;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
...
然后可以使用Linq来查询集合:
using System.Linq;
...
public static void Main(string[] args) {
LinkedList<int> list = ...
int a = 21;
var fr = list.start.FirstOrDefault(item => item.Value == a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.