Node *Reverse (Node *p)
{
Node *pr = NULL;
while (p != NULL)
{
Node *tmp = p->next;
p->next = pr;
pr = p;
p = tmp;
}
return pr;
}
Saturday, January 14, 2012
C program to count the number of set bits in an unsigned integer
/*
Program to count no. of bits in an unsigned integer
*/
void main( void )
{
unsigned int a = 15;
int count = 0;
while( a )
{
++count;
a = a & ( a - 1 );
}
clrscr();
printf( "Count is %d\n", count );
getch();
}
Program to count no. of bits in an unsigned integer
*/
void main( void )
{
unsigned int a = 15;
int count = 0;
while( a )
{
++count;
a = a & ( a - 1 );
}
clrscr();
printf( "Count is %d\n", count );
getch();
}
Why is sizeof('a') not 1?
Character constants in C are of type int, so sizeof('a') is sizeof(int) (though it's different in C++).
Result:
In Turbo C output is: 2
In Turbo C++ output is: 1
Result:
In Turbo C output is: 2
In Turbo C++ output is: 1
why n++ executes faster than n+1?
The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas, n+1 requires more instructions to carry out this operation.
Finding middle of the single linked list in a single traversal.
Step 1:
Take two pointers P1 and P2, both pointed to the first element.
Step 2:
Increment P1 by 1 and P2 by two.
Step 3:
Whenever P2 reaches to the end, P1 will be at the middle of the list, just return P1->data.
Take two pointers P1 and P2, both pointed to the first element.
Step 2:
Increment P1 by 1 and P2 by two.
Step 3:
Whenever P2 reaches to the end, P1 will be at the middle of the list, just return P1->data.
Finding Loop in a single linked list.
Method-1
If the linked list is read only, take two pointer approach( p1, p2). Both pointing to beginning of linked list. Now increment p1 by 1 and p2 by 2 and compare both. if they are equal there is a cycle. Repeat this untill p2 points to null.
Method-2
If you have the condition not to modify the node but you can change the links, then reverse the linked list. If you reach the head node then there is a cycle.
Difference between memcpy and memmove
memmove offers guaranteed behavior if the source and destination arguments overlap. memcpy makes no such guarantee, and may therefore be more efficiently implementable. When in doubt, it's safer to use memmove.
Subscribe to:
Posts (Atom)