我试图写一个从链表中删除节点的函数,虽然我遇到了麻烦。
这是我的算法:
例如
朋友 - >下一个=朋友 - >下一个 - >下..
虽然我需要找到链表中的第一个节点,但我不知道如何实现它。 这就是我写的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
typedef struct friend
{
char *name;
int age;
char gender;
struct friend* next;
}friend;
void node_delete(friend* delete)
{
friend* temp = malloc(sizeof(friend));
char name[256];
int i = 0, j =0; // Not being used, though I'd use it
printf ("Please enter the friend's name you want to delete: \n");
fgets (name, 256, stdin); // Getting the name of the person the user wants to delete
fgets (name, 256, stdin);
while (0 == (strcmp(temp -> next -> name, delete -> next -> name))) // As long as the
// name doesnt match, it'll go to the next name in the linked list
{
temp = friend -> next; // Going to the next name in the linked list
}
temp -> next = temp -> next -> next; // Replacing the node with the node after it..
// for ex. if I have 1 -> 2 -> 3, it'll be 1 -> 3
free (delete);
}
答案 0 :(得分:0)
好像你应该比较(temp - &gt; next - &gt; name)和(name),而不是(delete - &gt; next - &gt; name)
while (0 == (strcmp(temp -> next -> name, name)))
但你应该用你的朋友名单头
分配你的临时工具temp = delete; // delete should be a pointer to root list element
而且......出于什么原因你需要我和j? 为什么你使用malloc()?为什么不将你的结构声明为本地东西
friend* temp;
试试这个
friend* temp;
char name[256];
// receive node to delete
printf ("Please enter the friend's name you want to delete: \n");
// omg here was two fgets!!
fgets (name, 256, stdin);
// delete should be a pointer to root list element
temp = delete;
// Check if node to be deleted is a root node
if(strcmp(temp -> name, name)==0){
delete = delete->next;
return;
}
// go throug all the list
while (temp->next!=NULL){
// if node was found - delete it
if(strcmp(temp -> next -> name, name)==0)
temp -> next = temp -> next -> next;
temp = temp-> next;
}
此代码中存在逻辑错误,您还需要检查头节点。我的代码中没有这个检查。您可以自己轻松添加它。抱歉。 (已在代码块中修复)
此外,“删除”是函数参数的错误名称,请尝试使用friendList或类似的东西。另外不是在C ++中删除关键字?
答案 1 :(得分:0)
我不完全确定你的问题,但我认为你可能会尝试here。
它假设你的node_delete(friend* delete)
函数需要一个人,链接列表中有一些朋友,并删除一个名字与stdin输入相匹配的朋友。
(我还添加了另一个小功能,这样你就可以看到链表有多么有趣!)
顺便说一句,最好试试&amp;如果你想让民众帮忙,请确保你的代码编译; p 例如,temp = friend -> next;
将不编译。
祝你好运!