我在执行此任务时遇到问题。我只是获取列表,请检查其中是否包含当前处理的元素。如果是跳过它,否则添加到新列表。
我写了三个函数来做到这一点。搜索特定元素的一个元素,下一个正在检查元素的元素,它存在于新列表中,最后一个是将所有元素组合在一起。
我试图通过两种方式来做到这一点:
这是代码:
struct list *search_node(struct list *prt, char *to_search) {
is_empty();
short is_found = -1;
while (prt != NULL && ((is_found = strcmp(prt->word, to_search) != 0))) {
prt = prt->next;
}
if (!is_found)
return prt;
else
return NULL;
}
bool is_on_list(struct list *ptr, char *str) {
if (search_node(ptr, str) != NULL)
return 1;
else
return 0;
}
struct list *without_repetiton(struct list *head) {
struct list *new_list = NULL;
struct list **new_el = &new_list;
struct list *prt1 = head, *check;
while (prt1 != NULL) {
//printf("test = %s\n", prt1 -> word);
check = new_list;
if (!is_on_list(prt1->next, prt1->word)) { // or (new_list, prt1 -> word)
*new_el = (struct list *)malloc(sizeof(struct list));
memcpy(*new_el, prt1, sizeof(struct list));
new_el = &((*new_el)->next);
}
prt1 = prt1->next;
}
return new_list;
}
有清单的结构:
struct list {
char *word;
struct list *next;
struct list *prev;
};
我有两个问题,第一个为什么第一种方法以降序写入列表,第二个为什么当我试图在已创建的列表中搜索单词出现时却不起作用?
IO样本:
时间:
is_on_list(prt1->next, prt1->word))
拳头列表:一,二,二第二名单:二,一
时间:
is_on_list(new_list, prt1->word))
第一个列表与第二个相同。 最佳答案
您的代码无法正确构造重复列表:简化代码并手动链接新元素,而不是使用memcpy()
:
struct list *search_node(struct list *ptr, const char *to_search) {
while (ptr != NULL) {
if (!strcmp(ptr->word, to_search))
return ptr;
}
return NULL;
}
bool is_on_list(struct list *ptr, const char *str) {
return search_node(ptr, str) != NULL;
}
struct list *without_repetiton(struct list *head) {
struct list *new_list = NULL;
struct list *tail = NULL;
for (struct list *ptr = head; ptr != NULL; ptr = ptr->next) {
if (!is_on_list(new_list, ptr->word)) {
struct list *node = malloc(sizeof(*node));
node->next = NULL;
node->prev = tail;
node->str = strdup(ptr->word);
if (tail == NULL) {
new_list = tail = node;
} else {
tail->next = node;
tail = node;
}
}
}
return new_list;
}
关于c - 从链接列表中删除重复项,并将其保存到C中的另一个列表中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40976382/