-
Notifications
You must be signed in to change notification settings - Fork 4
/
urlsort.c
79 lines (67 loc) · 1.61 KB
/
urlsort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
struct param_node {
char *value;
struct param_node *right, *left;
};
typedef struct param_node Node;
static void insert(Node **tree, Node *item) {
if(!(*tree)) {
*tree = item;
return;
}
if(strcmp(item->value, (*tree)->value) > 0)
insert(&(*tree)->left, item);
else if(strcmp((*tree)->value, item->value) > 0)
insert(&(*tree)->right, item);
}
static void sortparam(Node *tree, char *out) {
if(tree->right) sortparam(tree->right, out);
strcat(out, tree->value);
strcat(out, "&\0");
if(tree->left) sortparam(tree->left, out);
}
void freetree(Node *root)
{
if(root!=NULL)
{
freetree(root->left);
freetree(root->right);
free(root);
}
}
static char * urlsort(char *in) {
Node *root, *current;
root = NULL;
char *url, *params;
url = strdup(in);
params = strchr(url, '?');
if(params == NULL) {
free(url);
free(params);
return in;
}
char *token, *sorted_params, *tmp;
sorted_params = (char*) malloc(strlen(in));
params[0] = '\0';
for(token = strtok_r(++params, "&", &tmp); token; token = strtok_r(NULL , "&", &tmp)) {
current = (Node* )malloc(sizeof(Node));
current->left = current->right = NULL;
if(token == NULL) break;
current->value = token;
insert(&root, current);
}
if(root == NULL) return in;
sorted_params[0] = 0;
sortparam(root, sorted_params);
strcat(url, "?");
sorted_params[strlen(sorted_params) - 1] = 0;
strcat(url, sorted_params);
free(token);
free(sorted_params);
free(tmp);
freetree(root);
return url;
}