跳過到頁腳內容
.NET幫助

C# Linked List(對於開發者的運行原理)

鏈結串列是一種由一系列節點構成的線性資料結構,也可以稱為元素。 與陣列不同,陣列中的元素/節點儲存在連續的記憶體位置,而鏈結串列利用動態記憶體配置,使元素/節點可以散佈於整個記憶體中。

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

  1. 資料:儲存在節點中的有效載荷。 這可以是依據實作而定的任何資料類型,例如整數、字串、物件等。
  2. 下一個指標:對序列中下一個節點的參考(或指標)。 這個指標指示下一個節點在鏈結串列中的記憶體位置指向前方。

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

In this article, we will look in detail at the Linked list in C# and also explore the IronPDF library, a PDF generation tool from Iron Software.

鏈結串列的類型

1. 單鏈結串列

單鏈結串列的節點只有一個指標,通常指向序列中的下一個節點。 遍歷列表僅限於一個方向,通常是從頭(初始節點)到尾(最後節點)。

2. 雙向鏈結串列

在雙向鏈結串列中,每個節點包含兩個指標:一個指向下一個節點,另一個指向序列中的上一個節點。 這種雙向連結使得可在正向和反向方向上遍歷。

3. 環鏈結串列

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

鏈結串列上的基本操作

  1. 插入:將一個新節點加入列表中的特定位置,例如開頭、結尾或中間。
  2. 刪除:從列表中移除指定的物件節點,並相應調整鄰近節點的指標。
  3. 遍歷:遍歷列表以訪問或操縱每個節點的資料。
  4. 搜尋:根據資料指定的值在列表中尋找特定節點。

C#中的鏈結串列

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

using System;
using 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
            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);
            }

            // Display number of linked list elements
            Console.WriteLine($"Number of Linked List elements: {linkedList.Count}");

            // Find/Search for an element in the linked list
            Console.WriteLine("\nFind/Search Element Linked List elements: 30");
            var foundNode = linkedList.Find(30);

            if (foundNode != null)
            {
                Console.WriteLine(
                    $"Found Value: {foundNode.Value}, " +
                    $"Next Element: {(foundNode.Next != null ? foundNode.Next.Value.ToString() : "null")}, " +
                    $"Previous Element: {(foundNode.Previous != null ? foundNode.Previous.Value.ToString() : "null")}"
                );
            }

            // Insert an element at a specified node
            LinkedListNode<int> current = linkedList.Find(20);
            if (current != null)
            {
                linkedList.AddAfter(current, 25);
            }

            Console.WriteLine($"\nNumber of Linked List elements: {linkedList.Count}");
            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);

            Console.WriteLine("\nLinked List elements after removal:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"\nNumber of Linked List elements: {linkedList.Count}");
        }
    }
}
using System;
using 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
            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);
            }

            // Display number of linked list elements
            Console.WriteLine($"Number of Linked List elements: {linkedList.Count}");

            // Find/Search for an element in the linked list
            Console.WriteLine("\nFind/Search Element Linked List elements: 30");
            var foundNode = linkedList.Find(30);

            if (foundNode != null)
            {
                Console.WriteLine(
                    $"Found Value: {foundNode.Value}, " +
                    $"Next Element: {(foundNode.Next != null ? foundNode.Next.Value.ToString() : "null")}, " +
                    $"Previous Element: {(foundNode.Previous != null ? foundNode.Previous.Value.ToString() : "null")}"
                );
            }

            // Insert an element at a specified node
            LinkedListNode<int> current = linkedList.Find(20);
            if (current != null)
            {
                linkedList.AddAfter(current, 25);
            }

            Console.WriteLine($"\nNumber of Linked List elements: {linkedList.Count}");
            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);

            Console.WriteLine("\nLinked List elements after removal:");
            foreach (var item in linkedList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine($"\nNumber of Linked List elements: {linkedList.Count}");
        }
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic

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
			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

			' Display number of linked list elements
			Console.WriteLine($"Number of Linked List elements: {linkedList.Count}")

			' Find/Search for an element in the linked list
			Console.WriteLine(vbLf & "Find/Search Element Linked List elements: 30")
			Dim foundNode = linkedList.Find(30)

			If foundNode IsNot Nothing Then
				Console.WriteLine($"Found Value: {foundNode.Value}, " & $"Next Element: {(If(foundNode.Next IsNot Nothing, foundNode.Next.Value.ToString(), "null"))}, " & $"Previous Element: {(If(foundNode.Previous IsNot Nothing, foundNode.Previous.Value.ToString(), "null"))}")
			End If

			' Insert an element at a specified node
			Dim current As LinkedListNode(Of Integer) = linkedList.Find(20)
			If current IsNot Nothing Then
				linkedList.AddAfter(current, 25)
			End If

			Console.WriteLine($vbLf & "Number of Linked List elements: {linkedList.Count}")
			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)

			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}")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

代碼說明

  1. 使用 new LinkedList<int>() 創建一個新的整数鏈結串列。
  2. 將指定值的物件添加到鏈結串列中。
  3. 使用 foreach 迴圈遍歷並列印鏈結串列的元素。
  4. 在鏈結串列中查找/搜尋一個元素。
  5. 使用 FindAddAfter 方法在指定節點插入一個元素。
  6. 使用 Remove 方法從鏈結串列中刪除現有節點。

輸出

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

介绍 IronPDF

Discover more about 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 支持不同的專案類型,如 Web 應用(Blazor 和 WebForms)、桌面應用(WPF 和 MAUI)和控制台應用。

內容來源

您可以從多種內容來源生成 PDF,包括 HTML 文件、Razor 檢視(Blazor 服務器)、CSHTML(MVC 和 Razor)、ASPX(WebForms)和 XAML(MAUI)。

額外功能

  1. 為 PDF 添加頁眉和頁腳。
  2. 合併、拆分、添加、複製和刪除 PDF 頁面。
  3. 設置密碼、權限和數位簽章。
  4. 利用多線程和異步支持優化性能。

兼容性

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

使用 LinkedList 生成 PDF 文件

現在讓我們來創建一個 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 System;
using System.Collections.Generic;
using IronPdf;

namespace 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>Create a new linked list of strings with new LinkedList&lt;string&gt;()</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>";
            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>";
            LinkedListNode<string> node = linkedList.Find("Banana");
            if (node != null)
            {
                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>";
            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 a PDF renderer
            var renderer = new ChromePdfRenderer();

            // Create a PDF from HTML string
            var pdf = renderer.RenderHtmlAsPdf(content);

            // Save to a file
            pdf.SaveAs("AwesomeIronOutput.pdf");
        }
    }
}
using System;
using System.Collections.Generic;
using IronPdf;

namespace 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>Create a new linked list of strings with new LinkedList&lt;string&gt;()</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>";
            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>";
            LinkedListNode<string> node = linkedList.Find("Banana");
            if (node != null)
            {
                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>";
            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 a PDF renderer
            var renderer = new ChromePdfRenderer();

            // Create a PDF from HTML string
            var pdf = renderer.RenderHtmlAsPdf(content);

            // Save to a file
            pdf.SaveAs("AwesomeIronOutput.pdf");
        }
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports IronPdf

Namespace 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>Create a new linked list of strings with new LinkedList&lt;string&gt;()</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>"
			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>"
			Dim node As LinkedListNode(Of String) = linkedList.Find("Banana")
			If node IsNot Nothing Then
				linkedList.AddAfter(node, "Mango")
				content &= "<p>Find Banana and insert Mango After</p>"
			End If

			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>"
			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 a PDF renderer
			Dim renderer = New ChromePdfRenderer()

			' Create a PDF from HTML string
			Dim pdf = renderer.RenderHtmlAsPdf(content)

			' Save to a file
			pdf.SaveAs("AwesomeIronOutput.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

代碼說明

  1. 首先,我們從創建 PDF 的內容開始,使用內容字符串物件。 內容生成為 HTML 字符串。
  2. 創建一個新的字串鏈結串列,使用 new LinkedList<string>()
  3. 向鏈結串列中添加元素,並將信息附加到 PDF 內容字符串。
  4. 列印鏈結串列的元素,並附加到 PDF 內容。
  5. 使用 AddAfter 方法在特定位置插入元素; 更新內容並列印結果列表。
  6. 使用 Remove 方法從鏈結串列中刪除元素,更新內容,並列印結果列表。
  7. 最後,使用 ChromePdfRendererRenderHtmlAsPdfSaveAs 方法將生成的 HTML 內容字符串保存為 PDF 文檔。

輸出

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

輸出帶有水印,可以通過從 IronPDF 授權頁面獲得有效許可證來刪除。

IronPDF 許可證

The IronPDF library requires a license to run, and it can be obtained from the product licensing page.

將密鑰粘貼到下面的 appSettings.json 文件中。

{
  "IronPdf.License.LicenseKey": "The Key Goes Here"
}

結論

C# LinkedList 提供了一種靈活的數據結構,用於管理元素集合,在允許動態調整大小的同時提供高效的插入和刪除,類似於默認哈希函數。 鏈結串列通常用於各種應用程序和算法中,例如實現堆疊、佇列、符號表和記憶體管理系統。 了解鏈結串列的特徵和操作對於構建高效且可擴展的軟件解決方案至關重要。

總之,儘管鏈結串列在某些場景中很出色,例如動態數據結構和頻繁的插入/刪除操作,但它們可能不適合需要頻繁隨機訪問或在記憶體受限的環境中使用的應用。 仔細考慮數據的具體需求和特點可以引導選擇最合適的數據結構來完成手頭的任務。

來自 Iron Software 的 IronPDF 庫允許開發人員輕鬆創建和操作 PDF 文件,從而開發現代應用程序的高級技能。

常見問題解答

什么是 C# 中的链表?

C# 中的链表是一种由节点组成的线性数据结构,每个节点包含数据和一个指向下一个节点的引用。与数组不同,这种结构允许动态内存分配,使得元素可以存储在非连续的内存位置。

怎樣在 C# 中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法将 HTML 字符串转换为 PDF。它还允许您使用 RenderHtmlFileAsPdf 将 HTML 文件转换为 PDF。

C# 中的链表类型有哪些?

在 C# 中,链表的主要类型有单链表、双向链表和循环链表。单链表的节点只有一个指向下一个节点的引用,双向链表有指向下一个和前一个节点的引用,循环链表的最后一个节点指向第一个节点。

可以对链表执行哪些基本操作?

链表支持的操作包括插入(添加新节点)、删除(移除现有节点)、遍历(迭代列表)以及搜索(根据节点数据查找节点)。

如何在 C# 中实现链表?

可以使用来自 System.Collections.Generic 命名空间的 LinkedList 类在 C# 中实现链表,该类提供了用于添加、删除和操作节点的方法。

PDF 生成库提供了哪些功能?

像 IronPDF 这样的 PDF 生成库提供 HTML 到 PDF 的转换、文本提取、文档合并和拆分、设置文档权限等功能,涵盖了各种 .NET 环境。

如何使用链表与 PDF 生成?

链表可以动态存储和组织内容,随后可以进行迭代,并使用像 IronPDF 这样的库将其转换为 PDF 文档,促进内容的操作和输出。

在软件开发中使用链表的优势是什么?

链表提供高效的插入和删除、动态调整大小,并且对于实现动态数据结构如栈和队列非常有益。尽管它们缺少随机访问能力,但在需要频繁修改时特别有用。

单链表和双向链表之间有什么区别?

主要区别在于单链表的节点只有一个指向下一个节点的引用,允许单向遍历,而双向链表的节点有指向下一个和前一个节点的引用,允许双向遍历。

如何在 C# 中从链表数据生成 PDF?

可以迭代链表以收集数据,然后使用 IronPDF 的 API 将这些数据渲染为 PDF 文档。这涉及使用像 HtmlToPdf 这样的方法将结构化内容转换为专业的 PDF 格式。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。