1.

Traverse Singly Linked List in C#

Answer»

A singly linked list is a linear data structure in which each node contains the data as well as the POINTER or reference to the next node in the list. There is no pointer or reference to the previous node in the singly linked list.

A program that demonstrates traversal in a singly linked list is GIVEN as follows:

using System; NAMESPACE Demo {    class singlelinkedlist    {        private INT data;        private singlelinkedlist next;        public singlelinkedlist()        {            data = 0;            next = null;        }        public singlelinkedlist(int num)        {            data = num;            next = null;        }        public singlelinkedlist InsertLast(int num)        {            singlelinkedlist newnode = new singlelinkedlist(num);            if (this.next == null)            {                newnode.next = null;                this.next = newnode;            }           else            {                singlelinkedlist temp = this.next;                newnode.next = temp;                this.next = newnode;            }            return newnode;        }        public void traversal(singlelinkedlist node)        {            if (node == null)                node = this;            System.Console.WriteLine("The linked list elements are:");            while (node != null)            {                System.Console.WriteLine(node.data);                node = node.next;            }        }    }    class Program    {        static void Main(string[] args)        {            singlelinkedlist node1 = new singlelinkedlist(9);            singlelinkedlist node2 = node1.InsertLast(1);            singlelinkedlist node3 = node2.InsertLast(5);            singlelinkedlist node4 = node3.InsertLast(7);            singlelinkedlist node5 = node4.InsertLast(2);            node1.traversal(null);        }

The output of the above program is as follows:

The linked list elements are: 9 1 5 7 2


Discussion

No Comment Found