using System; using System.Collections.Generic; using System.Text; namespace LinkedList_T_Sample { public class Document { private string title; public string Title { get { return title; } } private string content; public string Content { get { return content; } } private byte priority; public byte Priority { get { return priority; } } public Document(string title, string content, byte priority) { this.title = title; this.content = content; this.priority = priority; } } public class PriorityDocumentManager { private readonly LinkedList fullList = new LinkedList (); private readonly Listedlistnode> > priorityNodes;
public PriorityDocumentManager() { priorityNodes = new Listedlistnode> >(10); for (int i = 0; i < 10; i++) { priorityNodes.Add(new LinkedListNode (null)); } } public void AddDocument(Document 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) { AddDocumentToPriorityNode(doc, priority); } else { fullList.AddLast(doc); priorityNodes[doc.Priority] = fullList.Last; } return; } else { LinkedListNode priorityNode = priorityNodes[priority]; if (priority == doc.Priority) { fullList.AddAfter(priorityNode, doc); priorityNodes[doc.Priority] = priorityNode.Next; } else { LinkedListNode firstPriorityNode = priorityNode; while (firstPriorityNode.Previous != null && firstPriorityNode.Previous.Value.Priority == priorityNode.Value.Priority) { firstPriorityNode = priorityNode.Previous; } fullList.AddBefore(firstPriorityNode, doc); priorityNodes[doc.Priority] = firstPriorityNode.Previous; } } } public void DisplayAllNodes() { foreach (Document doc in fullList) { Console.WriteLine("priority:{0}, title {1}", doc.Priority, doc.Title); } } public Document GetDocument() { Document doc = fullList.First.Value; fullList.RemoveFirst(); return doc; } } class Program { static void Main(string[] args) { PriorityDocumentManager 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(); } } }
泛型LinkedList
最新推荐文章于 2023-06-27 22:29:33 发布