Sunday, February 25, 2007

Check If Cycle exists in a Linked List

Check if the linked list contains a cycle


using System;
using System.Collections.Generic;
using System.Text;

namespace Algorithms
{
public class LinkedList
{
private Node head;

public LinkedList()
{
head = null;
}


public bool CheckCycle()
{
Node step1Node = head;
Node step2Node = head.NextNode;

while (true)
{
if ((step2Node == null)||(step2Node.NextNode == null))
return false;
else if ((step1Node.Equals(step2Node))||(step1Node.Equals(step2Node.NextNode)))
return true;
else
{
step2Node = step2Node.NextNode;
step2Node = step2Node.NextNode;
step1Node = step1Node.NextNode;
}
}
}
public int FindPosition(int data)
{
Node checkNode = head;
int position = 1;
int dataPosition = 0;
while (checkNode != null)
{
if (checkNode.DataValue == data)
{
dataPosition = position;
}
checkNode = checkNode.NextNode;
position = position + 1;
}
return dataPosition;

}
}
public class Node
{
private int dataValue;
private Node nextNode = null;

public Node(int data)
{
dataValue = data;
}
public Node NextNode
{
get
{
return nextNode;
}
set
{
nextNode = value;
}
}
public int DataValue
{
get
{
return dataValue;
}
set
{
dataValue = value;
}
}

}
}

No comments: