跳至頁尾內容
開發者更新

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

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

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

  1. 資料:儲存在節點中的載體。 根據實作不同,這可以是任何資料型別,例如整數、字串、物件等。
  2. 下一個指標:指向序列中下一個節點的參考(或指標)。 此指標指示鏈結串列中後續節點的記憶體位置,朝前指向。

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

在本文中,我們將詳細介紹C#中的鏈結串列,並探索來自Iron SoftwareIronPDF程式庫,它是一種PDF生成工具。

鏈結串列的種類

1. 單向鏈結串列

單向鏈結串列的節點只有一個參考,通常指向序列中的下一個節點。 瀏覽列表僅限於單向移動,通常從頭(初始節點)到尾(最後節點)。

2. 雙向鏈結串列

在雙向鏈結串列中,每個節點包含兩個參考:一個指向下一個節點,另一個指向序列中的前一個節點。 這種雙向連結允許在前後兩個方向上瀏覽。

3. 環狀鏈結串列

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

鏈結串列的基本操作

  1. 插入:在列表中的特定位置新增一個新節點,如開頭、末尾或中間。
  2. 刪除:從列表中移除指定的物件節點,並相應地調整相鄰節點的指標。
  3. 遍歷:遍歷列表以存取或操作每個節點的資料。
  4. 搜尋:根據其資料指定的值找到列表中的特定節點。

Linked List in C

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

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. 使用AddAfter方法在指定節點插入元素。
  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支持不同的專案型別,例如Web應用(Blazor和WebForms)、桌面應用(WPF和MAUI)和控制台應用。

內容來源

您可以從各種內容來源生成PDF,包括HTML文件、Razor視圖(Blazor Server)、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文件

現在讓我們來建立一個使用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 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. 最後,使用SaveAs方法將生成的HTML內容字串保存為PDF文件。

輸出

C#鏈結串列(開發者如何運作):圖6 - IronPDF與`LinkedList`輸出

輸出有一個水印,可以使用有效的許可證從IronPDF許可證頁面中移除。

IronPDF許可證

IronPDF程式庫需要許可證才能運行,它可以從產品許可證頁面上獲得。

將金鑰粘貼到下面的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格式。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話