prioritydocumentmanager.cs
来自「C#高级编程第6版随书源代码 值得下载」· CS 代码 · 共 99 行
CS
99 行
using System;
using System.Collections.Generic;
using System.Text;
namespace Wrox.ProCSharp.Collections
{
public class PriorityDocumentManager
{
private readonly LinkedList<Document> documentList;
// priorities 0..9
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 d)
{
if (d == null) throw new ArgumentNullException("d");
AddDocumentToPriorityNode(d, d.Priority);
}
private void AddDocumentToPriorityNode(Document doc, int priority)
{
if (priority > 9 || priority < 0)
throw new ArgumentException("Priority must be between 0 and 9");
if (priorityNodes[priority].Value == null)
{
priority--;
if (priority >= 0)
{
// check for the next lower priority
AddDocumentToPriorityNode(doc, priority);
}
else // now no priority node exists with the same priority or lower
// add the new document to the end
{
documentList.AddLast(doc);
priorityNodes[doc.Priority] = documentList.Last;
}
return;
}
else // a priority node exists
{
LinkedListNode<Document> priorityNode = priorityNodes[priority];
if (priority == doc.Priority) // priority node with the same
// priority exists
{
documentList.AddAfter(priorityNode, doc);
// set the priority node to the last document with the same priority
priorityNodes[doc.Priority] = priorityNode.Next;
}
else // only priority node with a lower priority exists
{
// get the first node of the lower priority
LinkedListNode<Document> firstPriorityNode = priorityNode;
while (firstPriorityNode.Previous != null &&
firstPriorityNode.Previous.Value.Priority ==
priorityNode.Value.Priority)
{
firstPriorityNode = priorityNode.Previous;
}
documentList.AddBefore(firstPriorityNode, doc);
// set the priority node to the new value
priorityNodes[doc.Priority] = firstPriorityNode.Previous;
}
}
}
public void DisplayAllNodes()
{
foreach (Document doc in documentList)
{
Console.WriteLine("priority: {0}, title {1}", doc.Priority, doc.Title);
}
}
// returns the document with the highest priority (that's first
// in the linked list)
public Document GetDocument()
{
Document doc = documentList.First.Value;
documentList.RemoveFirst();
return doc;
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?