Archive for algorithms coding

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 != ”){
pSend++;
size++;
}
pSend–;
// reverese stentence
reversestr(pSstart,pSend);

while(wordstop < pSend)
{
//find the word
while((*wordstop!=”)&&(*wordstop!=’ ‘)) wordstop++;
wordstop–;
//reverese the word
reversestr(wordstart,wordstop);
wordstart = wordstop +2;
wordstop = wordstart;
}
}

Leave a Comment

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;
}

Leave a Comment

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
}

Leave a Comment

WAP to reverse a linked list?

void reverse(NODE **head) {
if (!*head) return;
NODE *cur = *head;
NODE *prev = NULL;
NODE *next = NULL;
while (cur) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
*head = prev;
return;

}

Recusive way call with original = list, parent = NULL

Node* reverselinkedlist(Node* original, Node*parent)
{
Node* reverse;

if(original == NULL)
{
reverse = parent;

}
else
{
reverse = reverselinkedlist(original->link,original);
original->link = parent;
}

return reverse;

}

Leave a Comment