Microsoft Interview Question
Software Engineer / Developersnum=12345
while ( num ! = 0)
{
mod = num % 10
num = num / 10
Append the num to linked list
}
struct node* createLinkList(int x){
node* first=NULL;
int temp;
while(x>0){
temp=x%10;
node* a=(node*)malloc(sizeof(struct node));
a->x=temp;
if(first==NULL)
a->next=NULL;
else
a->next=first;
first=a;
x=x/10;
}
return first;
}
typedef struct nodeT
{
int data;
nodeT *next;
}node;
void createLinkedList(int number)
{
int temp;
node *first = NULL;
while(x>0)
{
temp = x%10;
node *newNode = (node *)malloc(sizeof(node));
newNode->data = temp;
if(first == NULL)
{
newNode->next = NULL;
}else{
newNode->next = first;
}
first = newNode;
x = x/10;
}
return first;
}
16 node * getlist(unsigned n)
17 {
18 node * head = NULL;
19 do
20 {
21 unsigned digit = n%10;
22 n = n/10;
23 node * p = (node *)malloc(sizeof(node));
24 if(!p)
25 {
26 delete_list(head);
27 return NULL;
28 }
29 p->data = digit;
30 p->next = head;
31 head = p;
32 }while(n);
33 return head;
34 }
35
36 void delete_list(node * head)
37 {
38 node * curr = head;
39 while(curr)
40 {
41 node * next = curr->next;
42 free(curr);
43 curr = next;
44 }
45 }
46
algo
get the least significant digit by using successive modulo and / operator and keep pushing at the head end of the list.
Test cases
1. what to do when the number is negative...where to store the - sign
2. what if the value is 0. no need to perform the % and / operator. create a single node with data value equal to 0
3.what if the number is out of range
4. what if the number is float (given it is an unsigned int, but does your logic handle for a wrong input??)
5.check for memory allocation of the node, can be a failure sometimes
6.similarly check for a wrong input of characters instead of digits
class Node
{
public:
int val;
Node* next;
};
void Append(int val,Node** head)
{
if(*head == NULL)
{
Node* newn = new Node();
newn->val = val;
newn->next = NULL;
*head = newn;
}
else
{
Node* temp = *head;
Node* newn = new Node();
newn->val = val;
newn->next = temp;
*head = newn;
}
}
Node* Convertlist(int num)
{
Node* Head = NULL;
if(num<=0)
return NULL;
else
while(num)
{
int x = num%10;
Append(x,&Head);
num = num/10;
}
return Head;
}
1.store each remainder in linked list while num>0
- anon November 27, 2009num/=10;
2. reverse list