这是一个双向的链表,这个和c、c++中的类似,但是没有指针。也需要小心,因为一不小心就容易索引值溢出,写方法的时候要仔细。
using System;
using System.Collections.Generic;
namespace Sample
{
public class MainEntryPoint
{
static int Main(string[] args)
{
var pdm = new PriorityDocumentManager();
pdm.AddDocument(new Document("one","Sample",8));
pdm.AddDocument(new Document("two","Sample",3));
pdm.AddDocument(new Document("three","Sample",4));
pdm.AddDocument(new Document("four","Sample",8));
pdm.AddDocument(new Document("five","Sample",1));
pdm.AddDocument(new Document("six","Sample",9));
pdm.AddDocument(new Document("seven","Sample",1));
pdm.AddDocument(new Document("eight","Sample",1));
pdm.DisplayAllNodes();
return 0;
}
}
public class Document
{
public string Title{ get; private set;}
public string Content{ get; private set;}
public int Priority{ get; private set;}
public Document(string title, string content, int priority)
{
this.Title = title;
this.Content = content;
this.Priority = priority;
}
}
public class PriorityDocumentManager
{
private readonly LinkedList<Document> documentList;//链表的声明
private readonly List<LinkedListNode<Document>> priorityNodes;//优先权列表 放每个优先权 最后一个节点
public PriorityDocumentManager()
{
documentList = new LinkedList<Document>();//实例化链表
priorityNodes = new List<LinkedListNode<Document>>(10);//实例化列表
for(int i = 0; i < 10; i++)
{
priorityNodes.Add(new LinkedListNode<Document>(null));//初始化列表中的元素
}
}
public void AddDocument(Document doc)
{
if(doc == null)
throw new ArgumentNullException("doc");
AddDocumentToPriorityNode(doc, doc.Priority);
}
public void AddDocumentToPriorityNode(Document doc, int p)
{
if(p > 9 || p < 0)
throw new ArgumentException("Priority must be between 0 and 9");
//当优先权的列表相应位置没有元素 就进入
if(priorityNodes[p].Value == null)
{
--p;
//当优先权大于0的时候 继续调用自己 递归
if(p >= 0)
{
AddDocumentToPriorityNode(doc, p);
}
else
{
//进入这里说明这个优先权列表在这个优先权之后 全部都为空 此时把元素直接加入
//链表的最后即可
//把优先权列表的相应节点赋值
documentList.AddLast(doc);
priorityNodes[doc.Priority] = documentList.Last;
}
}
else
{
//当这个doc的优先权列表的节点上有值 或者 比它优先权小的节点上有值 就到这里了
//把这个有值得节点存到另外一个变量上
LinkedListNode<Document> prioNode = priorityNodes[p];
if(doc.Priority == p)
{
//当这个优先权的节点上有值 我们将把doc加到它后面
//这个优先权的最后一个值就是现在刚加入放入doc的引用
documentList.AddAfter( prioNode, doc);
priorityNodes[doc.Priority] = prioNode.Next;
}
else
{
//当这个优先权的节点比doc的小
//需要找到这个节点最前面的那一个节点
LinkedListNode<Document> firstNode = prioNode;
while(firstNode.Previous != null && firstNode.Previous.Value.Priority == prioNode.Value.Priority)
{
firstNode = prioNode.Previous;
prioNode = firstNode;
}
//把doc节点加在这个最前面的节点之前就可以了
//最后需要把优先权节点的值修改成这个doc的引用
documentList.AddBefore(firstNode, doc);
priorityNodes[doc.Priority] = firstNode.Previous;
}
}
}
public void DisplayAllNodes()
{
foreach(Document doc in documentList)
{
Console.WriteLine("priority {0},title {1}", doc.Priority, doc.Title);
}
}
public Document GetDocument()
{
Document doc = documentList.First.Value;
documentList.RemoveFirst();
return doc;
}
}
}