Implementing Circular Linked Lists in C#

implementing-circular-linked-lists-in-c

Implementing Circular Linked Lists in C#

I got this interesting implementation of circular linked lists in C# I was looking to do in one of my recent projects.

class CircularLinkedList {
    public static LinkedListNode<object> NextOrFirst(this LinkedListNode<object> current) {
        if (current.Next == null)
            return current.List.First;
        return current.Next;
    }

    public static LinkedListNode<object> PreviousOrLast(this LinkedListNode<object> current) {
        if (current.Previous == null)
            return current.List.Last;
        return current.Previous;
    }
}

The reason I liked this code is – 

As far as I can tell the only difference between a Linked List and a Circular Linked List is the behavior of iterators upon reaching the end or beginning of a list. A very easy way to support the behavior of a Circular Linked List is to write an extension method for a LinkedListNode that returns the next node in the list or the first one if no such node exists, and similarly for retrieving the previous node or the last one if no such node exists. The following code should accomplish that, although I haven’t tested it:

Now you can just call myNode.NextOrFirst() instead of myNode.Next and you will have all the behavior of a circular linked list. You can still do constant time removals and insert before and after all nodes in the list and the like. If there’s some other key bit of a circular linked list I am missing, let me know 🙂