Saturday, December 26, 2009

When to use 'Volatile' in C programming

http://clinuxpro.com/Cprogramming/volatile.php

No.of bits required to change to convert integer a to b

int BitSwapReqd(int a, int b)
{
int temp1=0;
int temp2=0;
int count=0;

while(a!=0 || b!=0)
{
temp1 = a & 1;
temp2 = b & 1;
a = a>>1;
b = b>>1;
if(temp1 != temp2)
count++;
}
return count;
}

Thursday, December 24, 2009

List Flattening

1. Creating list that needs to be list flattened


#include

using namespace std;
//Node struct used in list flattening
typedef struct node
{
unsigned int data;
struct node* prev;
struct node* next;
struct node* child;
}Node;
//Create a node and insert Data and NULL into pointers
Node* CreateNode(unsigned int uiData)
{
Node* aNode = new Node();
aNode->data = uiData;
aNode->next = aNode->prev = aNode->child = NULL;
return aNode;
}
//Recursive call, to create list
Node* CreateList(Node **Head, bool bNeedChild)
{
int iData;
Node* Curr=NULL,*Prev=NULL;
//Parent, keeps track of the node that is going to create child nodes
static Node *Parent = NULL;
while(true)
{
cout<<"Enter Node Data:"<
cin>>iData;
//return Head of the list
if(iData < 0)
{
return *Head;
}
//Creating child node


if(bNeedChild && Parent->child)
{
Parent->child = CreateNode(iData);
Curr = Parent->child;
}
//Create node with data inserted, and Prev=Next=Child=NULL
else
Curr = CreateNode(iData);


//If it is very first node the list
if(*Head == NULL)
Parent = *Head = Prev = Curr;
else if(Prev) //Establish connection, only if the there was a valid Previous node
{
Prev->next = Curr;
Curr->prev = Prev;
Prev = Curr;
}
//Ask if child should be created
cout<<"Do you want to create child to this node"<
cin>>bNeedChild;
if(bNeedChild == 1)
{
//Here, we are going to spawn a child for the current node,


//therefore mark it as Parent
Parent = Curr;
Curr->child = CreateList(&(Curr->child),bNeedChild);
continue;
}

else
Prev = Curr;
} //end of while(1)
return Curr;
}


void Display(Node* Head)
{
Node* Curr = Head;
while(Curr)
{
cout<data<<"\t";
if(Curr->child != NULL)
Display(Curr->child);
}
Curr = Curr->next;
}
}


int main()
{
Node *Head = NULL;
cout<<"List flattening Demo"<
Node* Tail = CreateList(&Head,0);
Display(Head);
return 0;
}
This code is not copied from anywhere, it is soley my handwritten code.

Not gurantee to be of any fault