C#集合之鏈表

来源:http://www.cnblogs.com/afei-24/archive/2017/05/09/6830160.html
-Advertisement-
Play Games

LinkedList<T>是一個雙向鏈表,其元素會指向它前面和後面的元素。這樣,通過移動到下一個元素可以正向遍歷鏈表,通過移動到前一個元素可以反向遍歷鏈表。 鏈表在存儲元素時,不僅要存儲元素的值,還必須存儲每個元素的下一個元素和上一個元素的信息。這就是LinkedList<T>包含LinkedLis ...


  LinkedList<T>是一個雙向鏈表,其元素會指向它前面和後面的元素。這樣,通過移動到下一個元素可以正向遍歷鏈表,通過移動到前一個元素可以反向遍歷鏈表。
  
  鏈表在存儲元素時,不僅要存儲元素的值,還必須存儲每個元素的下一個元素和上一個元素的信息。這就是LinkedList<T>包含LinkedListNode<T>類型的元素的原因。使用LinkedListNode<T>,可以獲得列表中的下一個和上一個元素。LinkedListNode<T>定義了屬性List,Next,Previous和Value。List屬性返回與節點相關的LinkedList<T>對象。Next和Previous屬性用於遍歷鏈表,訪問當前節點之後和之前的節點。Value屬性返回與節點相關的元素,其類型是T。
  鏈表的優點是,如果將元素插入到列表的中間位置,使用鏈表就會很快。在插入一個元素時,秩序啊喲修改上一個元素的Next引用和下一個元素的Previous引用,使它們引用所插入的元素。在  List<T>(http://www.cnblogs.com/afei-24/p/6824791.html)中,插入一個元素,需要移動該元素後面的所以元素。
  鏈表的缺點是,鏈表元素只能一個接一個的訪問,這需要較長時間來查找位於鏈表中間或尾部的元素。

  LinkedList<T>類定義的成員可以訪問鏈表中的第一個和最後一個元素(First和Last);
  在指定位置插入元素:AddAfter(),AddFirst()和AddLast();
  刪除指定位置的元素:Remove(),RemoveFirst(),RemoveLast();
  搜索:Find(),FindLast()。

  下麵用一個例子演示鏈表。在鏈表中,文檔按照優先順序來排序。如果多個文檔的優先順序相同,這些元素就按照文檔的插入時間來排序:
  PriorityDocumentManager類使用一個鏈表LinkedList<Document> documentList和一個列表List<LinkedListNode<Document>> priorityNodes,鏈表包含Document對象,Document對象包含文檔的標題和優先順序。列表List<LinkedListNode<Document>> priorityNodes應最多包含10個元素,每個元素分別是引用每個優先順序的最後一個文檔對象。
  

  

      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)
            {
              //Contract.Requires<ArgumentNullException>(d != null, "argument d must not be null");
              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");

              //檢查優先順序列表priorityNodes中是否有priority這個優先順序
              if (priorityNodes[priority].Value == null)
              {
                //如果沒有,遞減優先順序值,遞歸AddDocumentToPriorityNode方法,檢查是否有低一級的優先順序
                --priority;
                if (priority >= 0)
                {
                  AddDocumentToPriorityNode(doc, priority);
                }
                else //如果已經沒有更低的優先順序時,就直接在鏈表中添加該節點,並將這個節點添加到優先順序列表
                {
                  documentList.AddLast(doc);
                  priorityNodes[doc.Priority] = documentList.Last;
                }
                return;
              }
              else //優先順序列表priorityNodes中有priority這個優先順序
              {
                LinkedListNode<Document> prioNode = priorityNodes[priority];
                //區分優先順序列表priorityNodes存在這個指定的優先順序值的節點,還是存在較低的優先順序值的節點
                if (priority == doc.Priority)
                // 如果存在這個指定的優先順序值的節點
                {
                  //將這個節點添加到鏈表
                  documentList.AddAfter(prioNode, doc);

                  // 將這個節點賦予優先順序列表中的這個優先順序值的節點,因為優先順序節點總是引用指定優先順序節點的最後一個文檔
                  priorityNodes[doc.Priority] = prioNode.Next;
                }
                else //如果存在較低的優先順序值的節點
                {
                  //在鏈表中找到這個較低優先順序的第一個節點,把要添加的節點放到它前面
                  LinkedListNode<Document> firstPrioNode = prioNode;
                    //通過迴圈,使用Previous找到這個優先順序的第一個節點
                  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 (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;
            }

          }

          //存儲在鏈表中的元素是Document類型
          public 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)
            {
              this.Title = title;
              this.Content = content;
              this.Priority = priority;
            }
          }

 

客戶端代碼:
  

static void Main()
        {
          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();

          Console.ReadKey();

        }

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 更新yum # yum update 新建用戶 # adduser user設置密碼 # passwd user 允許用戶通過ssl遠程訪問 # vi /etc/ssh/sshd_config 在文末加上 AllowUsers user1 user2 修改許可權 # vi /etc/passwd 將U ...
  • ^ 一行的開始標誌如^bigeyyes匹配到所有以bigeyyes開頭的行 $ 一行的結束標誌如$bigeyyes 匹配到所有以bigeyyes結尾的行 ?或 . 匹配任意一個非換行字元,如big?eyes匹配到big後接一個任意字元,然後是eyyes的行 * 匹配任意0個或者多個字元 [xxx]或 ...
  • 新建一個空的項目 新建好了空的項目以後,接著通過NuGet安裝一下三個包 Nancy Nancy.Hosting.Aspnet Nancy.ViewEnglines.Razor 然後在項目中添加Models,Module,Views三個文件夾,併在Models中添加UserModel類 然後往Mod ...
  • 1. 原則 推薦以符合以下原則的方式編寫模板化控制項: 選擇合適的父類: 選擇合適的父類可以節省大量的工作,從UWP自帶的控制項中選擇父類是最安全的做法,通常的選擇是Control、ContentControl、ItemsControl,也可以選擇從RangeBase、Selector中。 代碼和UI分 ...
  • 我們想在一個文本框輸入一些文字,然後點擊銨鈕,alert()出來。 <div ng-app="alertApp" ng-controller="alertController"> <div> <label>Name:</label> <input type="text" ng-model="Name ...
  • 項目需求原因需要把Webapi中的Datetime 序列化及反序列化時間戳(long),遇到相同問題的同學可作參考。 1.聲明一個時間戳轉換器 2.配置使用時間戳轉換器(到這一步API就能序列化和反序列化時間戳了) 3.因為項目中使用了Swagger UI自動生成WebApi文檔如果想介面文檔Dat ...
  • 第一種方案: 用require吧 <configuration> ... <startup> <requiredRuntime version="4.0.30319" safemode="true"/> </startup> ... </configuration> 轉載自:https://soci ...
  • 如果需要基於鍵對所需集合排序,就可以使用SortedList<TKey,TValue>類。這個類按照鍵給元素排序。這個集合中的值和鍵都可以使用任何類型。定義為鍵的自定義類型需要實現IComparer<T>介面,用於給列表中的元素排序。 使用構造函數創建一個有序列表,在用Add方法添加: var bo ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...