Prasad Telkikar
Prasad Telkikar

Reputation: 16079

Can we assign address of two nodes as a next of a one LinkedListNode in C#?

I am solving one program from linked list data structure in c#, where I need to check that given linked list is NULL terminated or ends with cycle. I want to check it with different test cases, but not able to pass cyclic linked list as an input.

How to pass an cyclic linked list as an Input?

Problem from hackerrank will give you an idea, what I am trying to achieve?

Here is my code to achieve linked list showed in the image

private static LinkedList<int> InitializeLinkedList ()
        {
        LinkedList<int> linkedList = new LinkedList<int>();

        LinkedListNode<int> item1 = new LinkedListNode<int>(1);
        LinkedListNode<int> item2 = new LinkedListNode<int>(2);
        LinkedListNode<int> item3 = new LinkedListNode<int>(3);
        LinkedListNode<int> item4 = new LinkedListNode<int>(4);
        LinkedListNode<int> item5 = new LinkedListNode<int>(5);
        LinkedListNode<int> item6 = new LinkedListNode<int>(6);
        linkedList.AddLast(item1);
        linkedList.AddLast(item2);
        linkedList.AddLast(item3);
        linkedList.AddLast(item4);
        linkedList.AddLast(item5);
        linkedList.AddAfter(item3, item6);

        return linkedList;            
        }

Upvotes: -3

Views: 81

Answers (2)

Kevin Smith
Kevin Smith

Reputation: 14456

It's impossible to create a cycle, LinkedList<> are built up with LinkedListNode<> These Node contain the item value as well as the List, Next and Previous which are used for navigating, these members only have internal setters so you can't manually assign these. These are however set when we call AddFirst, AddLast, AddAfter or AddBefore on the LinkedList.

In theory we could set the First and Last to be the same LinkedListNode

        var item1 = new LinkedListNode<string>("one");
        var item2 = new LinkedListNode<string>("two");
        var item3 = new LinkedListNode<string>("three");

        var list = new LinkedList<string>();

        list.AddFirst(item1);
        list.AddAfter(item1, item2);
        list.AddAfter(item2, item3);
        list.AddLast(item1);

but If we try the following we'll get a "Unhandled Exception: System.InvalidOperationException: The LinkedList node already belongs to a LinkedList." Exception

Upvotes: 1

jdweng
jdweng

Reputation: 34421

Try following :

       static void Main(string[] args)
        {
            LinkedList<Node> ll = new LinkedList<Node>();

            Node node1 = new Node();
            Node node2 = new Node();
            Node node3 = new Node();

            ll.AddLast(node1);
            ll.AddLast(node2);
            ll.AddLast(node3);
            ll.AddLast(node2);

        }
        public class Node
        {
        }

Upvotes: -1

Related Questions