vekay
vekay

Reputation: 11

Converting singly linked list to circular linked list by pointing last node to middle node

Given a singly linked list and the middle node's number from the start, I am trying to create a circular singly linked list by pointing the last node to the middle one. I have written the following code:

private static void PointToMiddle(ref CustomLinkedList myll, int middleNodeNumber)
{
    CustomLinkedListNode currentNode = myll.Root;
    CustomLinkedListNode middleNode = null;
    for (int iCtr = 1; currentNode != null; iCtr++)
    {
        if (iCtr == middleNodeNumber)
            middleNode = currentNode;
        currentNode = currentNode.next;
    }
    currentNode = middleNode;
}

However the last node of the linkedlist is still pointing to null instead of middle node. I understand somewhere I am going wrong, I am unable find it. Please help.

Upvotes: 0

Views: 158

Answers (1)

Russ
Russ

Reputation: 4163

The only way you would be able to get this to work would be to change:

currentNode = middleNode

This line simply replaces the reference to the currentNode object to be the reference to the middleNode object.

You would need to change this to:

currentNode.Next = middleNode

Unfortunately--unless in your CustomLinkedListNode you've added a setter to the "Next" property, currentNode.Next is readonly, meaning you cannot set it. Thus what you want is not possible.

Upvotes: 1

Related Questions