public class OneWayLinkedList
public void CreateLoopForTest()
start.next.next.next.next = start.next;
public bool CheckForLoop()
Node oneIncrement = start;
Node twoIncrement = start;
while (oneIncrement != null && twoIncrement != null && twoIncrement.next != null)
oneIncrement = oneIncrement.next;
twoIncrement = twoIncrement.next.next;
if (oneIncrement == twoIncrement)
loopStart = GetLoopStartNode(twoIncrement);
private Node GetLoopStartNode(Node twoIncrement)
Node oneIncrement = start;
while (oneIncrement != twoIncrement)
oneIncrement = oneIncrement.next;
twoIncrement = twoIncrement.next;
public void AddAndPreserveOrder(int data)
Node newNode = new Node(data);
if (loopStart == null) CheckForLoop();
Node current = loopStart == null ?
start : data <= loopStart.data ?
while (next != loopStart)
newNode.next = loopStart;
public void PrintElements()
Console.Write("{0} ", temp.data);
public static void Main(string[] args)
OneWayLinkedList list = new OneWayLinkedList();
list.AddAndPreserveOrder(3);
list.AddAndPreserveOrder(5);
list.AddAndPreserveOrder(7);
list.AddAndPreserveOrder(2);
list.CreateLoopForTest();
list.AddAndPreserveOrder(6);
list.AddAndPreserveOrder(8);
list.AddAndPreserveOrder(-1);
list.AddAndPreserveOrder(3);
list.AddAndPreserveOrder(0);
list.AddAndPreserveOrder(4);