我正在尝试创建一个通用双向链表,但我无法理解它。有没有人有使用 C# 非常简单地实现双向链表的示例?
谢谢
最佳答案
下面是支持 Add()
、索引器和 ToString()
的简单通用双链表 - 其余部分留给读者作为练习 - 这应该给你一个想法。
public class LinkedList<T>
{
protected LinkedListNode<T> root = null;
protected LinkedListNode<T> last = null;
public LinkedList()
{
}
public string ToString()
{
StringBuilder sb = new StringBuilder();
var node = root;
while (node != null)
{
sb.Append("{ " + node.Data.ToString() + " } ");
node = node.Next;
}
return sb.ToString();
}
public T this[int index]
{
get
{
var node = GetAt(index);
if(node == null)
throw new ArgumentOutOfRangeException();
return node.Data;
}
set
{
var node = GetAt(index);
if (node == null)
throw new ArgumentOutOfRangeException();
node.Data = value;
}
}
private LinkedListNode<T> GetAt(int index)
{
var current = root;
for(int i=0;i<index;i++)
{
if (current == null)
return null;
current = current.Next;
}
return current;
}
public void Add(T data)
{
if (root == null)
{
root = new LinkedListNode<T>(data);
last = root;
}
else
{
last.Next = new LinkedListNode<T>(data);
last.Next.Previous = last;
last = last.Next;
}
}
}
public class LinkedListNode<T>
{
public T Data {get;set;}
public LinkedListNode(T data)
{
Data = data;
}
public LinkedListNode<T> Next { get; set; }
public LinkedListNode<T> Previous { get; set; }
}
关于c# - 创建一个易于理解的双向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5428275/