.NET HELP

C# Linked List (How It Works For Developers)

Published June 6, 2024
Share:

A linked list is a linear data structure composed of a series of nodes, which can also be called elements. Unlike arrays, where elements/nodes are stored in contiguous memory locations, linked lists utilize dynamic memory allocation, allowing elements/nodes to be scattered throughout memory.

In its simplest form, "linked lists" consist of nodes linked together linearly. Each node contains two main parts:

  1. Data: Payload stored in the node. This can be of any data type depending on the implementation, such as integers, strings, objects, etc.
  2. Next Pointer: A reference (or pointer) to the next node in the sequence. This pointer indicates the memory location of the following node points forward in the linked list.

The last node in a linked list typically points to a null reference, indicating the end of the list.

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.

Types of Linked Lists

1. Singly Linked List

A singly linked list has a node with only one reference, typically pointing to the next node in the sequence. Traversing the list is limited to moving in one direction, typically from the head (the initial node) to the tail (the final node).

2. Doubly Linked List

In a doubly linked list, each node contains two references: one pointing to the next node and another pointing to the previous node in the sequence. This bidirectional linkage enables traversal in both forward and backward directions.

3. Circular Linked List

In a circular linked list, the last node points back to the first node, forming a circular structure. This type of linked list can be implemented using either singly or doubly linked nodes.

Basic Operations on Linked Lists

  1. Insertion: Adding a new node to the list at a specific position, such as the beginning, end, or middle.
  2. Deletion: Removing a specified object node from the list, and adjusting the pointers of neighboring nodes accordingly.
  3. Traversal: Iterating through the list to access or manipulate each node's data.
  4. Search: Finding a specific node in the list based on its data-specified value.

Linked List in C#

In C#, you can implement a linked list using the LinkedList class from the System.Collections.Generic namespace. Here's an example of all the basic operations:

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#

Code Explanation

  1. Create a new linked list of integers using the new LinkedList<int>().
  2. Additional specified value objects to a linked list.
  3. Traverse and print the elements of the linked list using foreach loop.
  4. Find/search an element in the linked list.
  5. Insert an element at a specified node using the Find and AddAfter methods.
  6. Remove an existing node from the linked list using the Remove method.

Output

C# Linked List (How It Works For Developers): Figure 1 - Linked List Output

Introducing IronPDF

Discover more about IronPDF is a powerful C# PDF library developed and maintained by Iron Software. It provides a comprehensive set of features for creating, editing, and extracting content from PDF documents within .NET projects.

Key Points about IronPDF

HTML to PDF Conversion

IronPDF allows you to convert HTML content to PDF format. You can render HTML pages, URLs, and HTML strings into PDFs with ease.

Rich API

The library offers a user-friendly API that enables developers to generate professional-quality PDFs directly from HTML. Whether you need to create invoices, reports, or other documents, IronPDF simplifies the process.

Cross-Platform Support

IronPDF is compatible with various .NET environments, including .NET Core, .NET Standard, and .NET Framework. It runs on Windows, Linux, and macOS platforms.

Versatility

IronPDF supports different project types, such as web applications (Blazor and WebForms), desktop applications (WPF and MAUI), and console applications.

Content Sources

You can generate PDFs from various content sources, including HTML files, Razor views (Blazor Server), CSHTML (MVC and Razor), ASPX (WebForms), and XAML (MAUI).

Additional Features

  1. Add headers and footers to PDFs.
  2. Merge, split, add, copy, and delete PDF pages.
  3. Set passwords, permissions, and digital signatures.
  4. Optimize performance with multithreading and asynchronous support.

Compatibility

IronPDF adheres to PDF standards, including versions 1.2 to 1.7, PDF/UA, and PDF/A. It also supports UTF-8 character encoding, base URLs, and asset encoding.

Generate PDF Document Using LinkedList

Now let's create a PDF document using IronPDF and also demonstrate the usage of LinkedList strings.

To start with, open Visual Studio and create a console application by selecting from project templates as shown below.

C# Linked List (How It Works For Developers): Figure 2 - New Project

Provide a project name and location.

C# Linked List (How It Works For Developers): Figure 3 - Project Configuration

Select the required .NET version.

C# Linked List (How It Works For Developers): Figure 4 - Target Framework

Install IronPDF from the Visual Studio Package manager like the one below.

C# Linked List (How It Works For Developers): Figure 5 - Install IronPDF

Or it can be installed using the below command line.

dotnet add package IronPdf --version 2024.4.2

Add the below code.

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#

Code Explanation

  1. First, we start by creating the content for the PDF, using a content string object. The content is created as an HTML string.
  2. Create a new linked list of strings with a new LinkedList<string>().
  3. Add elements to the linked list and also to the PDF content string.
  4. Print the elements of the linked list.
  5. Insert an element at a specific position using the AddAfter method and print the resulting list.
  6. Remove an element from the linked list using the Remove method and print the resulting list.
  7. Finally, save the generated HTML content string to a PDF document using ChromePdfRenderer, RenderHtmlAsPdf, and SaveAs methods.

Output

C# Linked List (How It Works For Developers): Figure 6 - IronPDF with `LinkedList` Output

The output has a watermark that can be removed using a valid license from the IronPDF licensing page.

IronPDF License

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

Paste the key in the appSettings.json file below.

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

Conclusion

C# LinkedList provides a versatile data structure for managing collections of elements, offering efficient insertions and deletions while accommodating dynamic resizing similar to the default hash function. Linked lists are commonly used in various applications and algorithms, such as implementing stacks, queues, symbol tables, and memory management systems. Understanding the characteristics and operations of linked lists is essential for building efficient and scalable software solutions.

In summary, while linked lists excel in certain scenarios, such as dynamic data structures and frequent insertions/deletions, they may not be the best choice for applications requiring frequent random access or dealing with memory-constrained environments. Careful consideration of the specific requirements and characteristics of the data can guide the selection of the most appropriate data structure for the task at hand.

The IronPDF library from Iron Software allows developers to create and manipulate PDF documents effortlessly, enabling advanced skills to develop modern applications.

< PREVIOUS
C# Reverse String (How It Works For Developers)
NEXT >
C# iList (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >