Search Bhai

 

Visitors

Given a single linked list write a function to swap each pair of nodes by manipulating with pointers (not values).?

Sol:
Original list: head->1->2->3->4->5->NIL should be transformed to head->2->1->4->3->5-> NIL

int reverse_pairs(LLIST ** head)
{
LLIST * temp = ULL;
LLIST* current_pair = *head;
LLIST** previouspair = head;
while((current_pair != NULL) && (current_pair->next != NULL))
{
temp = current_pair;
current_pair = current_pair->next;
temp->next = current_pair->next;
current_pair->next = temp;
*previouspair = current_pair;
current_pair = temp->next;
previouspair = &temp->next;
}
return 0;
}

Given a singly linked list, find the middle of the list?

Sol:
We can solve this easily using Hare and Tortoise approach. Basically have 2 pointers both pointing to the start of the list. Increment one pointer by 1 and
another by 2. When pointer 2 reaches end of the list pointer 1 will be in the middle of the linked list.

Node *FindMiddle( Node *head )
{
Node *p1, p2;
p1 = p2 = head;
while( p2 && p2->next )
{
p2 = p2->next->next;
p1 = p1->next;
}
return( p1 );
}

Reverse each individual word in sentence?

void reversestr(char* str, char* strend)
{
char tmp;
while(strend>str)
{
tmp = *strend;
*strend = *str;
*str = tmp;
str++;
strend--;
}
return;
}
void reverseSen(char *sentence)
{
char *wordstart=sentence, *wordstop=sentence;
char *pSend=sentence,*pSstart =sentence ;
int size=0;
while(*pSend != '\0'){
pSend++;
size++;
}
pSend--;
// reverese stentence
reversestr(pSstart,pSend);

while(wordstop < pSend)
{
//find the word
while((*wordstop!='\0')&&(*wordstop!=' ')) wordstop++;
wordstop--;
//reverese the word
reversestr(wordstart,wordstop);
wordstart = wordstop +2;
wordstop = wordstart;
}
}

Find out if a string is a palindrome?

bool Palindrome(char *str)

{
int end = strlen(str)-1;
for (int i = 0; i <>
if (*(str+i) != *(str+end))
return false;
return true;
}

Find a repeated integer in array of size n?

int DuplicatedNumber(int *a, int size)
{
map hash;
bool founddup = false;
for(int i=0; i 0)
{
founddup= true;
break;
}
else
hash[a[i]]++;
}

return founddup ? a[i] : -1; // return the duplicated value or -1 if not found
}

Giving Two Strings, Find out whether they are Anagrams(made up of same chars) or not?

If(strlen(Str1)!=strlen(Str2)) return FALSE;
sort both Str1,Str2.
If(str1==str2) return TRUE;
else
return FALSE;
Your Ad Here

Xcel-Online

Rent A Coder