Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Hi Anonymous,
Even I expected the output to be straightforward as you mentioned above, like
30->40->50->10->20
but this wasn't the case in the question. It was in random order like I mentioned in the question which made me little puzzled.
I think, perhaps we have to do multiple such rotations for K times to arrive at the solution..
struct Node * swap(struct Node *TT)
{
struct Node *L, *t;
if(TT)
{
if((TT->nxt)->nxt!=NULL)
{
L=(TT->nxt)->nxt;
printf(" %d ",L->val);
t=swap((L->nxt)->nxt);
(L->nxt)->nxt=TT;
(TT->nxt)->nxt=t;
return L;
}
else
{
return TT;
}
}
else
return NULL;
}
_myList * rotateList(int i, _myList *node)
{
static _myList*retNode=NULL;
if(i == 0 || node == NULL)
return retNode;
else
{
_myList *elementToAdd=node;
node=node->next;
elementToAdd->next=NULL;
retNode=node;
while(node->next) node = node->next;
node->next=elementToAdd;
rotateList(--i, retNode);
}
}
I am confused here. May be have not understood the question. When I rotate anything it will end up with the same data, in same order. Please let me know if we are talking about shifting instead of rotating.
may be the question is some thing like this (I got this below question while reading some other post. Pasting here as you said you are not sure what was the question)
FYR,
Reverse a Linked List in groups of given size
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).
Example:
Inputs: 1->2->3->4->5->6->7->8->NULL and k = 3
Output: 3->2->1->6->5->4->8->7->NULL.
Inputs: 1->2->3->4->5->6->7->80->NULL and k = 5
Output: 5->4->3->2->1->8->7->6->NULL.
ListNode* Solution::rotateRight(ListNode* A, int B) {
ListNode* p = A;
int len=0;
while (p!=NULL){
len++;
p=p->next;
}
int r;
if (B%len==0){
return A;
}else{
r = len-(B%len)-1;
}
p=A;
while (r>0){
p=p->next;
r--;
}
ListNode *q =p->next;
if (q==NULL){return A;}
while (q->next!=NULL){
q=q->next;
}
q->next = A;
q=p->next;
p->next=NULL;
return q;
}
ListNode* Solution::rotateRight(ListNode* A, int B) {
ListNode* p = A;
int len=0;
while (p!=NULL){
len++;
p=p->next;
}
int r;
if (B%len==0){
return A;
}else{
r = len-(B%len)-1;
}
p=A;
while (r>0){
p=p->next;
r--;
}
ListNode *q =p->next;
if (q==NULL){return A;}
while (q->next!=NULL){
q=q->next;
}
q->next = A;
q=p->next;
p->next=NULL;
return q;
}
if i understand your question you mean like
- Anonymous October 06, 2012if input is 10->20->30->40->50
then output should be like 30->40->50->10->20 (for k =3)
if this is the case then this can be done finding the 3rd node in the list from the last
so in our case it is 30 and the last node we have is 50. now simply we need to set the last node next to head and previous valus of the 3rd node from the last that is 20 should be set to NULL . now make the 3rd node from the last that is 30 to be the head of the link list.