C# - Traverse the Singly Linked List

Here, we are going to learn how to traverse the singly linked list in C#? By Nidhi Last updated : March 28, 2023

Traverse the Singly Linked List

Here, we will create a ListNode class that contains item and next pointer, and then add items to the list and traverse the list.

C# program to traverse the singly linked list

The source code to traverse the singly linked list is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

// C# - Traverse the Singly Linked List 

using System;

class ListNode {
  private int item;
  private ListNode next;

  public ListNode(int value) {
    item = value;
    next = null;
  }
  public ListNode AddItem(int value) {
    ListNode node = new ListNode(value);
    if (this.next == null) {
      node.next = null;
      this.next = node;
    } else {
      ListNode temp = this.next;
      node.next = temp;
      this.next = node;
    }
    return node;
  }

  public void ListTraverse() {
    ListNode node = this;

    while (node != null) {
      Console.WriteLine("-->" + node.item);
      node = node.next;
    }
  }
}

class Demo {
  static void Main(string[] args) {
    ListNode StartNode = new ListNode(201);

    ListNode n1;
    ListNode n2;
    ListNode n3;
    ListNode n4;

    n1 = StartNode.AddItem(202);
    n2 = n1.AddItem(203);
    n3 = n2.AddItem(204);
    n4 = n3.AddItem(205);

    Console.WriteLine("Traversing of Linked list:");
    StartNode.ListTraverse();
  }
}

Output

Traversing of Linked list:
-->201
-->202
-->203
-->204
-->205
Press any key to continue . . .

Explanation

In the above program, we created a ListNode class that contains data member's item and next. As we know that the node of a linked list contains item and pointer to the next node.

The ListNode class contains two constructors, AddItem() and ListTraverse() methods. The AddItem method is used to add items into the node that it will return the address of the node.

The ListTraverse() method is used to traverse the list from the start node to the end of the node in the linked list.

Now look to the Demo class that contains the Main() method. Here, we created the nodes using ListNode class and then add items and link the node to make a Linked List. After that, we finally traverse the list from start to end and printed the items on the console screen.

C# Data Structure Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.