我试图编写一个从链表中删除节点的函数,尽管我遇到了麻烦。
这是我的算法:
- 获取我要删除的节点的名称(每个节点都有 3 个详细信息:名称/年龄/性别)
- 然后我在列表中找到它的位置
- 然后我把它向前传递
例如
朋友->下一个=朋友->下一个->下一个..
虽然我需要在链表中找到第一个节点,但我不知道如何找到它。这是我写的:
#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);
}