How would you find a cycle in a linked list?
Answers were Sorted based on User's Feedback
Answer / sujith
Simultaneously go through the list by ones (slow iterator)
and by twos (fast iterator). If there is a loop the fast
iterator will go around that loop twice as fast as the slow
iterator. The fast iterator will lap the slow iterator
within a single pass through the cycle. Detecting a loop is
then just detecting that the slow iterator has been lapped
by the fast iterator.
This solution is "Floyd's Cycle-Finding Algorithm" as
published in "Non-deterministic Algorithms" by Robert W.
Floyd in 1967. It is also called "The Tortoise and the Hare
Algorithm"
| Is This Answer Correct ? | 11 Yes | 2 No |
Answer / jaroosh
The above method is working of course, but is not the most
efficient. Other methods are however quite complex and not
so easy to explain.
Anyway, to exemplify this aforementioned method, maybe not
the most efficient code, but off the top of my head, hope
there are no misspellings.
bool isCyclic(LinkedNode *list)
{
if(list == NULL || list->next == NULL) return false;
LinkedNode *node1 = list, *node2 = node1->next;
while(node1 != node2)
{
if(node1==NULL || node2==NULL || node2->next == NULL)
return false;
node1 = node1->next;
node2= node2->next->next;
}
return true;
}
NOTE: the assumption is that for noncyclic list, the last
node has next pointer set to NULL.
| Is This Answer Correct ? | 6 Yes | 7 No |
Answer / amit
the last node of the list will have address of first node
then it is a cycle linked list.
| Is This Answer Correct ? | 4 Yes | 11 No |
Explain the bubble sort algorithm.
main() { int a = 65; printf(“%d %o %x”,a,a,a); } Output 65 101 41 Please explain me.How it is coming like that?
Should a function contain a return statement if it does not return a value?
int main() { int i=-1,j=-1;k=0,l=2,m; m=i++&&j++&&k++||l++; printf("%d%d%d%d%d",i,j,k,l,m); }
Write a C program to help a HiFi’s Restaurant automate its breakfast billing system. Your assignment should implement the following items: a. Show the customer the different breakfast items offered by the HiFi’s Restaurant. b. Allow the customer to select more than one item from the menu. c. Calculate and print the bill to the customer. d. Produce a report to present your complete program and show more sample output. Assume that the HiFi’s Restaurant offers the following breakfast menu: Plain Egg $2.50 Bacon and Egg $3.45 Muffin $2.20 French Toast $2.95 Fruit Basket $3.45 Cereal $0.70 Coffee $1.50 Tea $1.80
#define MAX 3 main() { printf("MAX = %d ",MAX ); #undef MAX #ifdef MAX printf("Vector Institute”); #endif }
12345 1234 123 12 1
what different between c and c++
Can a variable be both constant and volatile?
Explain which function in c can be used to append a string to another string?
Explain in detail how strset (string handling function works )pls explain it with an example.
simple c program for 12345 convert 54321 with out using string