我写了这段代码,我想知道我的问题是什么,如果你可以帮我修复我写的一个你自己的代码,它会帮助我很多... 编辑:我已将其更改为此,现在它不会给我一个运行时错误,但是当我打印名称,或检查节点是否存在时,它说它是......
void node_delete(friend *amit) // Deleting a node
{
friend* temp;
int flag = 0;
while (head != NULL) // As long the node isnt the last one
{
if (0 == (strcmp(head -> next -> name, amit -> name))) // If the name that the user entered matchs a name in the linked list,
{ // It'll skip it
temp = head -> next;
head -> next = head -> next -> next; // Deletes a node from the linked list
flag = 1;
}
if (flag == 1) break;
head = head -> next; // Going to the next node
}
free(temp); // Freeing the deleted node
printf ("%s\n", amit -> name);
}
并在主要内容:
amit.name = "amit"
amit.age = 16
amit.gender = 'm'
node_delete(&amit);
和结构定义:
typedef struct friend // The struct
{
char *name;
int age;
char gender;
struct friend* next; // A pointer that points to the next node in the linked list
}friend;
非常感谢:)
答案 0 :(得分:1)
以下是前几行的一些评论:
head = amit;
head -> next = amit; // same as amit->next = amit;
amit -> next = NULL; // same as head->next = null;
while (head -> next != NULL) // will never do anything since head->next is null
答案 1 :(得分:0)
void node_delete(char *name)
{
friend *tmp, **p;
for (pp = &root; (tmp = *pp) ; pp = &tmp->next)
{
if (strcmp(tmp->name, name)) continue; // No match: walk on
printf("Deleted %s\n", tmp->name);
*pp = temp->next;
free(tmp);
break;
}
}
(假设指向链表头部的全局根指针) 被称为:
node_delete("Amit");
答案 2 :(得分:0)
friend *head = NULL;
...
add(data) {
friend *next = malloc(sizeof(bla));
fill(next, data);
if (head == NULL)
head = next;
else {
next->next = head;
head = next;
}
}
del(data) {
if (head) {
if (your_check(head, data)) {
to_free = head;
head = head->next;
free(to_free);
} else {
friend *list = head;
while (list->next) {
if (your_check(list->next, data)) {
to_free = list->next;
list->next = list->next->next;
free(to_free);
}
list = list->next;
}
}
}
}