給定字符串數組,去除重複項並保持原始輸入順序。C 標準庫無現成 Map/Set,需自行實現。
struct Node {
const char *sorted_str; // 排序用副本
const char *original_str; // 原始指針
int tag; // 1=保留 0=刪除
struct Node *self; // 指向原始位置
};
self 指向自身sorted_str 冒泡排序tag=0self 鏈),輸出 tag=1 的項int cmp_node(void *a, void *b) {
Node *n1 = (Node*)a, *n2 = (Node*)b;
int res = strcmp(n1->sorted_str, n2->sorted_str);
if (res == 0) n2->self->tag = 0; // 標記刪除
return res;
}
void swap_node(void *a, void *b) {
Node *n1 = (Node*)a, *n2 = (Node*)b, *tmp = n1->self;
const char *ts = n1->sorted_str;
n1->sorted_str = n2->sorted_str; n1->self = n2->self;
n2->sorted_str = ts; n2->self = tmp;
}
struct TreeNode {
struct StrNode *str_node; // 指向原始數組元素
struct TreeNode *left, *right;
};
TreeNode* add_node(TreeNode *root, StrNode *new_node, cmp_fn cmp) {
if (!root) {
root = calloc(1, sizeof(TreeNode));
root->str_node = new_node;
return root;
}
int r = cmp(new_node, root->str_node);
if (r == 0) { new_node->tag = 0; return root; } // 重複標記
if (r < 0) root->left = add_node(root->left, new_node, cmp);
else root->right = add_node(root->right, new_node, cmp);
return root;
}
tag 輸出摘自 黎明的豐收