问题描述
我想创建一个链接的列表只是为了看看我能做到,我无法让我的头周围。有没有人有使用C#一个非常简单的实现链表的例子吗?到目前为止,我已经找到了所有的例子都相当过头了。
I am trying to create a linked list just to see if I can, and I am having trouble getting my head around it. Does anyone have an example of a very simple implementation of Linked list using C#? All the examples I have found so far are quite overdone.
推荐答案
一个链表,其核心是联系在一起一串节点。
A Linked List, at its core is a bunch of Nodes linked together.
所以,你需要开始用一个简单的Node类:
So, you need to start with a simple Node class:
public class Node {
public Node next;
public Object data;
}
那么你的链表将作为一个成员的一个节点重新presenting列表的头部(开始):
Then your linked list will have as a member one node representing the head (start) of the list:
public class LinkedList {
private Node head;
}
然后,你需要通过添加方法将功能添加到列表中。他们通常涉及某种穿越沿所有节点。
Then you need to add functionality to the list by adding methods. They usually involve some sort of traversal along all of the nodes.
public void printAllNodes() {
Node cur = head;
while (cur.next != null)
{
Console.WriteLine(cur.data);
cur = cur.next;
}
}
此外,插入新的数据是另一种常见的操作:
Also, inserting new data is another common operation:
public void Add(Object data) {
Node toAdd = new Node();
toAdd.data = data;
Node current = head;
// traverse all nodes (see the print all nodes method for an example)
current.Next = toAdd;
}
这应该提供一个良好的起点。
This should provide a good starting point.
这篇关于创建一个非常简单的链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!