Document类:
class Document { public string Title { get; private set; } public string Content { get; private set; } public byte Priority { get; private set; } public Document(string title, string content, byte priority = 0) { this.Title = title; this.Content = content; this.Priority = priority; } }
PriorityDocumentManager类:
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); } private void AddDocumentToPriorityNode(Document doc, int priority) { if (priority > 9 || priority < 0) { throw new ArgumentException("优先级必须大于0小于9"); } if (priorityNodes[priority].Value == null) { --priority; if (priority >= 0) { AddDocumentToPriorityNode(doc, priority); } else { documentList.AddLast(doc); priorityNodes[doc.Priority] = documentList.Last; } return; } else { LinkedListNode<Document> prioNode = priorityNodes[priority]; if (priority == doc.Priority) { documentList.AddAfter(prioNode, doc); priorityNodes[doc.Priority] = prioNode.Next; } else { LinkedListNode<Document> firstPrioNode = prioNode; while (firstPrioNode.Previous != null && firstPrioNode.Previous.Value.Priority == prioNode.Value.Priority) { firstPrioNode = prioNode.Previous; prioNode = firstPrioNode; } documentList.AddBefore(firstPrioNode, doc); priorityNodes[doc.Priority] = firstPrioNode.Previous; } } } public void DisplayAllNodes() { foreach (var 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; } }
应用层:
PriorityDocumentManager pdm = new PriorityDocumentManager(); pdm.AddDocument(new Document("one", "content", 3)); pdm.AddDocument(new Document("two", "content", 1)); pdm.AddDocument(new Document("three", "content", 2)); pdm.AddDocument(new Document("six", "content", 4)); pdm.DisplayAllNodes();
附上应用层运行结果的截图:
时间: 2024-10-31 08:34:44