You will need some RAM for that if you don't have a Visited property on each item in the linked list.
If you have a Visited property you will first need to clear it before running the algorithm. This will probably not fit your big-O requirements.
It's not clear what you mean with "points at previous list item". Is equal by reference (object) or same value/set of property values (struct)? I assume reference. The code below can easily be modified to handle structs as well.
static void Main(string[] args)
{
var list = BuildALinkedListFromSomeData();
var isConsitent = IsConsistent(list);
}
static bool IsConsistent(LinkedList<Item> list)
{
var visited = new List<LinkedListNode<Item>>()
var runner = list.First;
while(runner != null)
{
if (visited.Contains(runner))
return false;
visited.Add(runner);
runner = runner.Next;
}
return true;
}
A O(n) solution that uses an existing numeric VisitCounter that already uses storage space (no additional storage needed):
static bool IsConsistent(LinkedList<Item> list)
{
var runner = list.First;
if (runner == null)
return false; // Assume consistent if empty
var consistent = true;
var runId = runner.Value.VisitCount;
while (runner != null)
{
// Does the traversed item match the current run id?
if(runner.Value.VisitCount > runId)
{
// No, Flag list as inconsistent. It must have been visited previously during this run
consistent = false;
// Reset the visit count (so that list is ok for next run)
runner.Value.VisitCount = runId;
}
// Increase visit count
runner.Value.VisitCount++;
// Visit next item in list
runner = runner.Next;
}
return consistent;
}
This makes changes to the content of an item in the list, but not the list itself. If you're not allowed to change the content of an item in the list, then of course this is not a solution either. Well, second-thought, this is not a possible solution at all. When inconsistent, your list is circular and the last algorithm will never finish :)
You will then have to traverse the list backwards from each visited item in your list and this will break your O(n+1) requirement.
Conclusion: Not so Mission Impossible if Count is available. See GrahamS' answer