.NET 幫助

C# 鏈結串列(開發人員如何使用)

發佈 2024年6月6日
分享:

鏈結串列是一種由一系列節點組成的線性數據結構,這些節點也可以稱為元素。與元素/節點存儲在連續內存位置的陣列不同,鏈結串列使用動態內存分配,允許元素/節點分散在內存中。

在其最簡單的形式中,"鏈結串列"由線性連結的節點組成。每個節點包含兩個主要部分:

  1. 數據:存儲在節點中的有效負載。這可以是任何數據類型,取決於實現,例如整數、字符串、對象等。

  2. 下一個指針:一個引用 (或指針) 到序列中的下一個節點。該指標指示下一個節點在鏈表中指向前方的記憶體位置。

鏈表中的最後一個節點通常指向一個空引用,表示列表的結尾。

在本文中, 我們將詳細探討 C# 中的鏈表 並且 IronPDF,來自 的 PDF 生成庫 Iron Software.

鏈結串列的種類

1. 單向鏈結串列

單向鏈結串列中的節點僅具有一個引用,通常指向序列中的下一個節點。遍歷鏈結串列僅限於向一個方向移動,通常是從頭節點開始。 (初始節點) 到尾部 (最終節點).

2. 雙向鏈結串列

在雙向鏈結串列中,每個節點包含兩個引用:一個指向下一個節點,另一個指向序列中的前一個節點。這種雙向鏈接允許進行前向和後向的遍歷。

3. 環狀連結列表

在環狀連結列表中,最後一個節點指向第一個節點,形成一個環狀結構。這種類型的連結列表可以使用單向或雙向連結節點來實現。

基本連結串列操作

  1. 插入:在特定位置(如開頭、結尾或中間)加入新節點到串列中。

  2. 刪除:從串列中移除指定的對象節點,並相應地調整相鄰節點的指標。

  3. 遍歷:迭代串列以存取或操作每個節點的數據。

  4. 搜尋:根據數據指定的值找到串列中的特定節點。

C# 中的連結串列

在 C# 中,您可以使用 連結串列 來自 System.Collections.Generic 命名空間的類。以下是所有基本操作的範例:

namespace CsharpSamples
{
public class Program
{
    public static void Main()
        {
            // Create a new linked list of integers
            LinkedList<int> linkedList = new LinkedList<int>();
            // Add elements to the linked list which create objects from node class
            linkedList.AddLast(10);
            linkedList.AddLast(20);
            linkedList.AddLast(30);
            linkedList.AddLast(40);
            // Traverse and Print the elements of the linked list
            Console.WriteLine("Traverse Linked List elements:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine($"Number of Linked List elements:{linkedList.Count}"); // use count property to display length
            // Find/Search Element in Linked List
            Console.WriteLine("\nFind/Search Element Linked List elements: 30");
            var foundNode = linkedList.Find(30);// method returns the node
            Console.WriteLine($"Found Value:{foundNode.Value}, Next Element:{foundNode.Next.Value}, Previous Element:{foundNode.Previous.Value}"); // prints next node, previous node
            // Insert an element at a specified node
            LinkedListNode<int> current = linkedList.Find(20);
            linkedList.AddAfter(current, 25);
            Console.WriteLine($"\nNumber of Linked List elements:{linkedList.Count}"); // use count property to display length
            Console.WriteLine("\nLinked List elements after insertion:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            // Remove an existing node from the linked list 
            linkedList.Remove(30); // remove current node
            Console.WriteLine("\nLinked List elements after removal:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine($"\nNumber of Linked List elements:{linkedList.Count}"); // use count property to display length
        }
    }
}
namespace CsharpSamples
{
public class Program
{
    public static void Main()
        {
            // Create a new linked list of integers
            LinkedList<int> linkedList = new LinkedList<int>();
            // Add elements to the linked list which create objects from node class
            linkedList.AddLast(10);
            linkedList.AddLast(20);
            linkedList.AddLast(30);
            linkedList.AddLast(40);
            // Traverse and Print the elements of the linked list
            Console.WriteLine("Traverse Linked List elements:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine($"Number of Linked List elements:{linkedList.Count}"); // use count property to display length
            // Find/Search Element in Linked List
            Console.WriteLine("\nFind/Search Element Linked List elements: 30");
            var foundNode = linkedList.Find(30);// method returns the node
            Console.WriteLine($"Found Value:{foundNode.Value}, Next Element:{foundNode.Next.Value}, Previous Element:{foundNode.Previous.Value}"); // prints next node, previous node
            // Insert an element at a specified node
            LinkedListNode<int> current = linkedList.Find(20);
            linkedList.AddAfter(current, 25);
            Console.WriteLine($"\nNumber of Linked List elements:{linkedList.Count}"); // use count property to display length
            Console.WriteLine("\nLinked List elements after insertion:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            // Remove an existing node from the linked list 
            linkedList.Remove(30); // remove current node
            Console.WriteLine("\nLinked List elements after removal:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine($"\nNumber of Linked List elements:{linkedList.Count}"); // use count property to display length
        }
    }
}
Imports Microsoft.VisualBasic

Namespace CsharpSamples
Public Class Program
	Public Shared Sub Main()
			' Create a new linked list of integers
			Dim linkedList As New LinkedList(Of Integer)()
			' Add elements to the linked list which create objects from node class
			linkedList.AddLast(10)
			linkedList.AddLast(20)
			linkedList.AddLast(30)
			linkedList.AddLast(40)
			' Traverse and Print the elements of the linked list
			Console.WriteLine("Traverse Linked List elements:")
			For Each item In linkedList
				Console.WriteLine(item)
			Next item
			Console.WriteLine($"Number of Linked List elements:{linkedList.Count}") ' use count property to display length
			' Find/Search Element in Linked List
			Console.WriteLine(vbLf & "Find/Search Element Linked List elements: 30")
			Dim foundNode = linkedList.Find(30) ' method returns the node
			Console.WriteLine($"Found Value:{foundNode.Value}, Next Element:{foundNode.Next.Value}, Previous Element:{foundNode.Previous.Value}") ' prints next node, previous node
			' Insert an element at a specified node
			Dim current As LinkedListNode(Of Integer) = linkedList.Find(20)
			linkedList.AddAfter(current, 25)
			Console.WriteLine($vbLf & "Number of Linked List elements:{linkedList.Count}") ' use count property to display length
			Console.WriteLine(vbLf & "Linked List elements after insertion:")
			For Each item In linkedList
				Console.WriteLine(item)
			Next item
			' Remove an existing node from the linked list 
			linkedList.Remove(30) ' remove current node
			Console.WriteLine(vbLf & "Linked List elements after removal:")
			For Each item In linkedList
				Console.WriteLine(item)
			Next item
			Console.WriteLine($vbLf & "Number of Linked List elements:{linkedList.Count}") ' use count property to display length
	End Sub
End Class
End Namespace
VB   C#

代碼說明

  1. 使用新的 LinkedList 創建一個新的整數鏈接列表()`

  2. 在鏈結串列中新增指定的數值物件

  3. 使用 foreach 循環遍歷並打印鏈結串列中的元素

  4. 在鏈結串列中查找/搜索元素

  5. 使用 FindAddAfter 方法在指定節點插入元素

  6. 使用 Remove 方法從鏈結串列中移除現有的節點

輸出

C# 鏈結串列(開發人員如何使用):圖 1 - 鏈結串列輸出

介紹 IronPDF

IronPDF 是由Iron Software開發和維護的強大C# PDF庫。它提供了一套全面的功能,用於在.NET項目中創建、編輯和提取PDF文檔內容。

IronPDF 的關鍵點

HTML 轉換為 PDF

IronPDF 可以幫助您將 HTML 內容轉換為 PDF 格式。您可以輕鬆地將 HTML 頁面、URL 和 HTML 字串渲染成 PDF。

豐富的 API

該庫提供了一個用戶友好的 API,使開發人員能夠直接從 HTML 生成專業品質的 PDF。無論您需要創建發票、報告或其他文件,IronPDF 都能簡化這個過程。

跨平台支援

IronPDF 與各種 .NET 環境相容,包括 .NET Core、.NET Standard 和 .NET Framework。它可在 Windows、Linux 和 macOS 平臺上執行。

多功能性

IronPDF 支援不同的專案類型,例如網頁應用程式 (Blazor和WebForms)桌面應用程式 (WPF 和 MAUI),和控制台應用程式。

內容來源

您可以從各種內容來源生成PDF,包括HTML文件、Razor視圖 (Blazor 伺服器), CSHTML (MVC 和 Razor), ASPX (網頁表單)和XAML (MAUI).

額外功能

  1. 添加PDF的頁首和頁尾。

  2. 合併、拆分、添加、複製和刪除PDF頁面。

  3. 設置密碼、權限和數字簽名。

  4. 透過多線程和異步支持優化性能。

相容性

IronPDF 遵循 PDF 標準,包括版本 1.2 到 1.7、PDF/UA 和 PDF/A。它還支持 UTF-8 字元編碼、基礎 URL 和資源編碼。

使用 LinkedList 生成 PDF 文件

現在讓我們使用 IronPDF 創建一個 PDF 文件,並演示 LinkedList 字串的使用。

首先,打開 Visual Studio,並從項目範本中選擇建立一個控制台應用程式,如下所示。

C# 鏈結串列(它如何為開發人員工作):圖 2 - 新專案

請提供專案名稱和位置。

C# 連結串列(開發人員是如何運作的):圖3 - 項目配置

選擇所需的 .NET 版本。

C# 鏈結列表 (開發人員如何使用它):圖 4 - 目標框架

從 Visual Studio 套件管理器中安裝 IronPDF,如下所示。

C# 鏈結串列(開發者該如何使用):圖 5 - 安裝 IronPDF

或者可以使用以下命令行安裝。

dotnet add package IronPdf --version 2024.4.2

加入以下程式碼。

using CsharpSamples;
public class Program
{
    public static void Main()
    {
            var content = "<h1>Demonstrate IronPDF with C# LinkedList</h1>";
            content += "<h2>Create a new linked list of strings</h2>";
            content += "<p></p>";
            content += "<p>Create a new linked list of strings with new LinkedList<string>()</p>";
            // Create a new linked list of strings
            LinkedList<string> linkedList = new LinkedList<string>();
            // Add elements to the linked list
            content += "<p>Add Apple to linkedList</p>";
            linkedList.AddLast("Apple");
            content += "<p>Add Banana to linkedList</p>";
            linkedList.AddLast("Banana");
            content += "<p>Add Orange to linkedList</p>";
            linkedList.AddLast("Orange");
            content += "<h2>Print the elements of the linked list</h2>";
            // Print the elements of the linked list
            Console.WriteLine("Linked List elements:");
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            content += "<h2>Insert an element at a specific position</h2>";
            // Insert an element at a specific position
            LinkedListNode<string> node = linkedList.Find("Banana");
            linkedList.AddAfter(node, "Mango");
            content += "<p>Find Banana and insert Mango After</p>";
            Console.WriteLine("\nLinked List elements after insertion:");
            content += "<h2>Linked List elements after insertion:</h2>";
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            content += "<h2>Remove an element from the linked list</h2>";
            // Remove an element from the linked list
            linkedList.Remove("Orange");
            content += "<p>Remove Orange from linked list</p>";
            Console.WriteLine("\nLinked List elements after removal:");
            content += "<h2>Linked List elements after removal:</h2>";
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            // create Renderer
            var renderer = new ChromePdfRenderer();
            // Create a PDF from HTML string
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Save to a file or Stream
            pdf.SaveAs("AwesomeIronOutput.pdf");        
    }
}
using CsharpSamples;
public class Program
{
    public static void Main()
    {
            var content = "<h1>Demonstrate IronPDF with C# LinkedList</h1>";
            content += "<h2>Create a new linked list of strings</h2>";
            content += "<p></p>";
            content += "<p>Create a new linked list of strings with new LinkedList<string>()</p>";
            // Create a new linked list of strings
            LinkedList<string> linkedList = new LinkedList<string>();
            // Add elements to the linked list
            content += "<p>Add Apple to linkedList</p>";
            linkedList.AddLast("Apple");
            content += "<p>Add Banana to linkedList</p>";
            linkedList.AddLast("Banana");
            content += "<p>Add Orange to linkedList</p>";
            linkedList.AddLast("Orange");
            content += "<h2>Print the elements of the linked list</h2>";
            // Print the elements of the linked list
            Console.WriteLine("Linked List elements:");
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            content += "<h2>Insert an element at a specific position</h2>";
            // Insert an element at a specific position
            LinkedListNode<string> node = linkedList.Find("Banana");
            linkedList.AddAfter(node, "Mango");
            content += "<p>Find Banana and insert Mango After</p>";
            Console.WriteLine("\nLinked List elements after insertion:");
            content += "<h2>Linked List elements after insertion:</h2>";
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            content += "<h2>Remove an element from the linked list</h2>";
            // Remove an element from the linked list
            linkedList.Remove("Orange");
            content += "<p>Remove Orange from linked list</p>";
            Console.WriteLine("\nLinked List elements after removal:");
            content += "<h2>Linked List elements after removal:</h2>";
            foreach (var item in linkedList)
            {
                content += $"<p>{item}</p>";
                Console.WriteLine(item);
            }
            // create Renderer
            var renderer = new ChromePdfRenderer();
            // Create a PDF from HTML string
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Save to a file or Stream
            pdf.SaveAs("AwesomeIronOutput.pdf");        
    }
}
Imports Microsoft.VisualBasic
Imports CsharpSamples
Public Class Program
	Public Shared Sub Main()
			Dim content = "<h1>Demonstrate IronPDF with C# LinkedList</h1>"
			content &= "<h2>Create a new linked list of strings</h2>"
			content &= "<p></p>"
			content &= "<p>Create a new linked list of strings with new LinkedList<string>()</p>"
			' Create a new linked list of strings
			Dim linkedList As New LinkedList(Of String)()
			' Add elements to the linked list
			content &= "<p>Add Apple to linkedList</p>"
			linkedList.AddLast("Apple")
			content &= "<p>Add Banana to linkedList</p>"
			linkedList.AddLast("Banana")
			content &= "<p>Add Orange to linkedList</p>"
			linkedList.AddLast("Orange")
			content &= "<h2>Print the elements of the linked list</h2>"
			' Print the elements of the linked list
			Console.WriteLine("Linked List elements:")
			For Each item In linkedList
				content &= $"<p>{item}</p>"
				Console.WriteLine(item)
			Next item
			content &= "<h2>Insert an element at a specific position</h2>"
			' Insert an element at a specific position
			Dim node As LinkedListNode(Of String) = linkedList.Find("Banana")
			linkedList.AddAfter(node, "Mango")
			content &= "<p>Find Banana and insert Mango After</p>"
			Console.WriteLine(vbLf & "Linked List elements after insertion:")
			content &= "<h2>Linked List elements after insertion:</h2>"
			For Each item In linkedList
				content &= $"<p>{item}</p>"
				Console.WriteLine(item)
			Next item
			content &= "<h2>Remove an element from the linked list</h2>"
			' Remove an element from the linked list
			linkedList.Remove("Orange")
			content &= "<p>Remove Orange from linked list</p>"
			Console.WriteLine(vbLf & "Linked List elements after removal:")
			content &= "<h2>Linked List elements after removal:</h2>"
			For Each item In linkedList
				content &= $"<p>{item}</p>"
				Console.WriteLine(item)
			Next item
			' create Renderer
			Dim renderer = New ChromePdfRenderer()
			' Create a PDF from HTML string
			Dim pdf = renderer.RenderHtmlAsPdf(content)
			' Save to a file or Stream
			pdf.SaveAs("AwesomeIronOutput.pdf")
	End Sub
End Class
VB   C#

代碼說明

  1. 首先,我們從建立 PDF 的內容開始,使用內容字串對象。內容被創建為 HTML 字串。

  2. 使用新的 LinkedList 創建一個新的字串鏈表。()`.

  3. 將元素添加到鏈結串列並添加到 PDF 內容字串中。

  4. 列印鏈結串列中的元素。

  5. 使用 AddAfter 方法在特定位置插入一個元素並列印結果串列。

  6. 使用 Remove 方法從鏈結串列中刪除一個元素並列印結果串列。

  7. 最後,使用 ChromePdfRendererRenderHtmlAsPdfSaveAs 方法將生成的 HTML 內容字串儲存為 PDF 文件。

輸出

C# 鏈結串列(開發人員如何使用):圖6 - 使用 `LinkedList` 輸出的 IronPDF

輸出包含浮水印,可以使用有效的許可證來移除。 授權頁面.

IronPDF License

IronPDF 該函式庫需要授權才能運行。

試用授權可在 試用授權頁面將金鑰貼在以下的 appSettings.json 文件中。

{
  "IronPdf.License.LicenseKey" = "The Key Goes Here"
}
{
  "IronPdf.License.LicenseKey" = "The Key Goes Here"
}
If True Then
  "IronPdf.License.LicenseKey" = "The Key Goes Here"
End If
VB   C#

結論

C# 的 LinkedList 提供了一種多功能的資料結構來管理元素集合,能夠有效地進行插入和刪除,同時可以像默認的哈希函數一樣適應動態調整大小。連結串列在各種應用和算法中很常見,如實現堆疊、佇列、符號表和記憶體管理系統。理解連結串列的特性和操作對於構建高效且具擴展性的軟體解決方案至關重要。

總而言之,儘管連結串列在某些情境中表現出色,如動態資料結構和頻繁的插入/刪除操作,但對於需要頻繁隨機訪問或處理記憶體受限環境的應用來說,它們可能不是最佳選擇。仔細考慮資料的具體需求和特性可以指導您選擇最合適的資料結構來完成當前任務。

Iron Software 的 IronPDF 庫可以讀取和生成 PDF 文件,幫助開發人員獲得開發現代應用的高級技能。

< 上一頁
C# 字串反轉(開發者指南)
下一個 >
C# iList(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >