我试图从用户那里获得输入,然后将结构追加到链表的末尾。这很好,但我想添加另一个功能,如果所有细节都完全相同,它将阻止添加输入。(在这种情况下,电子邮件、班级、名字和姓氏(
我在中间添加的for循环是我试图实现这一功能的。程序进入循环没有任何问题,但输入仍然会被添加。我该怎么解决这个问题?
struct request *append(struct request *list){
char f_name[NAME_LEN+1];
char l_name[NAME_LEN+1];
char e_address[EMAIL_LEN+1];
char c_name[CLASS_LEN+1];
//get input
printf("nEnter email: ");
scanf("%s", e_address);
printf("nEnter class: ");
scanf("%s", c_name);
printf("nEnter child first name: ");
scanf("%s", f_name);
printf("nEnter child last name: ");
scanf("%s", l_name);
//allocate memory for the structure
struct request* p = (struct request*) malloc(sizeof(struct request));
struct request *temp = list;
//////////WHAT I TRIED BUT DIDN'T WORK
for (p = list, temp = NULL; p != NULL; temp = p, p = p -> next) {
if (strcmp(p -> first, f_name) == 0 && strcmp(p -> last, l_name) == 0 && strcmp(p -> email, e_address) == 0 && strcmp(p -> class, c_name) == 0) {
printf("Output: request already exists");
return list;
}
}
//store the data
strcpy(p->first, f_name);
strcpy(p->last, l_name);
strcpy(p->email, e_address);
strcpy(p->class, c_name);
p->next = NULL;
//if list is empty return pointer to the newly created linked list
if (list == NULL) {
return p;
}
//traverse to the end of the list and append the new list to the original list
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = p;
return list;
}
首先,对于那些scanf,您应该这样做以避免缓冲区溢出。
至于你的问题,你应该在for循环之后对p
进行malloc,因为我们只应该在没有其他节点具有完全相同的信息的情况下分配它(正如paddy所说,在你的代码中,它会导致内存泄漏,因为你将p
设置为指向其他节点,从而丢失了新的malloc数据(。
你的循环比它需要的更复杂。诚然,我不明白为什么for循环不能检测到副本,也许提供一些输入案例会帮助清除它?无论哪种方式,我都会用以下代码替换该部分:
// Get a pointer to the head of the list
struct request *temp = list;
// Find and node with the exact same data
while(temp->next != NULL) {
if(!strcmp(temp->first, f_name) && !strcmp(temp->last, l_name) && !strcmp(temp->email, e_address) && !strcmp(temp->class, c_name)){
printf("Output: request already exists");
return list;
}
temp = temp->next;
}
// Allocate p and reset temp
struct request *p = (struct request*) malloc(sizeof(struct request));
temp = list;
// etc