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

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

Question:
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 InitializeLinkedList ()
{
LinkedList linkedList = new LinkedList();

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

return linkedList;
}


Answer:
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("one");
var item2 = new LinkedListNode("two");
var item3 = new LinkedListNode("three");

var list = new LinkedList();

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
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *