Monday, December 3, 2007

Linked List Circular or Not?

Given a pointer to the head of a link list write a function that returns 0 if the linked list ends in NULL or 1 if it is a circular linked list. Note that a final node in a circular link list doesn't necessarily point to the first node, but could point to any node in the list.

Part 1) Write a function that solves the problem in O(n^2)
Part 2) Write a function that solves the problem in O(n)

Friday, April 13, 2007

Greater of two numbers

I come across many programming puzzles. So I have decided to collect most of them at this place. Hope you like the puzzles. I start with a simple puzzle which is asked in many IT companies as an interview question.

Is there any way of finding the greater of two numbers without using any logical operators?

Yeah there is. It's pretty straight forward:

max(a,b) = 1/2(a+b + abs(a-b)); abs(x) being the absolute value of x.

That's because,

If a > b, 1/2(a+b + a-b) = a.

If b > a, 1/2(a+b + b-a) = b.

Another one I can think of is the following - though it involves the use of an if block:

if(abs(a-b)-(a-b))
{
  //Code of a < b follows
}
else
{
  //Code of a >= b follows
}

Please suggest any others you can think of.