Q:

C# program to traverse the singly linked list

0

C# program to traverse the singly linked list

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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# program to 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Data Structure Solved Programs/Examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to delete a given node from the singly ... >>
<< C# program to implement In-order traversal in Bina...