Microsoft Interview Question
Software Engineer in Testsraj that code doesn't work very well, first it only detects cycles that include the head node, plus it is really inefficient in the number of checks. something like this is better but doesn't have any cycle checks as I don't want to put it in. But go for it, here is a framework.
int traverse_list(node* n)
{
while(n) {
printf("%d", n->value);
n = n->next;
}
return 0;
}
Raj,
You are the biggest moron I have seen .Your check for finding cycle is wrong. Can this find the cycle with 1 2 3 1 . No it can't because each time first node will be one behind the second node owing to which it will keep revolving inside the loop without detecting. Get your concepts clear and then posts the solutions.
Assumptions
1. Singly Linked List.
2. Do not print complete list in case of Loop.
Scenarios
1. Empty List
2. Loop in the List.
3. n>0, elements in the list.
4. Memory corrupted node.
void TraverseList(NODE head)
{
NODE ptr1,ptr2;
ptr1= head;
if(NULL == ptr1) return;
ptr2 = head->next;
while(ptr1!=ptr2)
{
ptr1=ptr1->next;
if(ptr2) ptr2=ptr2->next;
if(ptr2) ptr2=ptr2->next;
Print ptr1;
}
if(ptr1)
Print Loop found
}
Please add memory corrupt detection code in it.
How about this?
- raj November 07, 2008TraverseList (Node head)
{
Node n1, n2;
n1 = head;
if (n1 == null) return;
n2 = n1;
Print n2.value;
while (n2.next != null && n2.next != n1)
{
n2 = n2.next;
print n2.value;
}
}