cosmin
BAN USERSolution in C:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *left;
struct Node *right;
} Node;
static Node* dokth_largest(Node* n, unsigned int* k)
{
if ( ! k )
return NULL;
Node* tmp = NULL;
if ( n->left )
tmp = dokth_largest(n->left, k);
if ( tmp )
return tmp;
if ( *k == 0 )
return n;
--(*k);
if ( n->right )
tmp = dokth_largest(n->right, k);
return tmp;
}
Node* kth_largest(Node *root, unsigned int k)
{
return dokth_largest(root, &k);
}
int main()
{
Node n1 = { 1, NULL, NULL };
Node n3 = { 3, NULL, NULL };
Node n2 = { 2, &n1, &n3 };
Node n5 = { 5, NULL, NULL };
Node n6 = { 6, &n5, NULL };
Node n4 = { 4, &n2, &n6 };
Node* n = kth_largest(&n4, 4);
if ( n )
printf("%d\n", n->val);
else
printf("not found\n");
}
In C:
// Represent binary least significant bit first.
typedef struct Node
{
int bit;
struct Node* next;
} Node;
Node* add(Node* l1, Node* l2)
{
Node* ret = NULL;
Node* tail = NULL;
int carry = 0;
while ( l1 || l2 )
{
int r = (l1 ? l1->bit : 0) + (l2 ? l2->bit : 0) + carry;
r = r % 2;
carry = r / 2;
Node* tmp = (Node*)malloc(sizeof(Node));
tmp->bit = r;
if ( tail )
{
tail->next = tmp;
tail = tail->next;
}
else
{
tail = tmp;
ret = tail;
}
if ( l1 )
l1 = l1->next;
if ( l2 )
l2 = l2->next;
}
if ( carry )
{
Node* tmp = (Node*)malloc(sizeof(Node));
tmp->bit = carry;
tail->next = tmp;
tail = tmp;
}
return ret;
}
Brute-force approach, C code:
#include <stdio.h>
#include <string.h>
const char* maxword(const char* words[], int len, const char* letters)
{
int maxsize = 0;
const char* maxw = NULL;
int i;
for ( i = 0; i < len; ++i )
{
const char* word = words[i];
const char* wordletter = word;
int cont = 1;
int localsize = 0;
while ( *wordletter++ && cont )
{
const char* l = letters;
while ( *l++ )
{
if ( *wordletter == *l )
++localsize;
}
}
if ( localsize > maxsize )
{
maxsize = localsize;
maxw = word;
}
}
return maxw;
}
int main()
{
const char* words[] = { "abacus",
"deltoid",
"gaff",
"giraffe",
"microphone",
"reef",
"qar" };
const char* word = maxword(words, 7, "aeffgirq");
printf("%s\n", word);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void* mymemmove(void* dest, void* source, size_t num)
{
unsigned char* destc = (unsigned char*)dest;
unsigned char* sourcec = (unsigned char*)source;
for ( ; num > 0; --num )
{
destc[num-1] = sourcec[num-1];
}
return destc;
}
int main()
{
char* str = (char*)malloc(100);
memset(str, 0, 100);
strcpy(str, "memmove can be very useful......");
mymemmove(str+20, str+15, 11);
puts(str);
free(str);
return 0;
}
Solution in C that finds the first suitable path:
- cosmin March 20, 2013