从链表更新数据
Update data from linked list
我正在为一个项目制作一些链表。我已经编写了一个添加列表
t_team *add_team(t_team *teams, char *team_name, int id)
{
t_team *tmp;
if ((tmp = malloc(sizeof(t_team))) == NULL)
return (NULL);
if ((tmp->name = malloc(sizeof(char) * strlen(team_name) + 1)) == NULL)
return (NULL);
strcpy(tmp->name, team_name);
tmp->id = id;
tmp->next = teams;
return (tmp);
}
但是我需要更新列表中一个特定节点的 ID,我该怎么做?
谢谢
第 1 步:找到您要更新的列表
t_team *find_by_name(t_team *head, char *team_name)
{
t_team * tmp = head;
while(tmp != NULL){
if(strcmp(tmp->name, team_name) != 0)
head = tmp->next; //Advance the pointer to next element
else
return tmp;
}
return NULL;
}
第 2 步:更新字段
从您的主要功能调用此实用程序:-
t_team *tmp = find_by_name(head, "Some_Name");
if( tmp == NULL)
//element not found
else
tmp->id = new_id; //Update ID
更新:- 更新了 find_by_name 以使用 tmp 而不是修改 head
我正在为一个项目制作一些链表。我已经编写了一个添加列表
t_team *add_team(t_team *teams, char *team_name, int id)
{
t_team *tmp;
if ((tmp = malloc(sizeof(t_team))) == NULL)
return (NULL);
if ((tmp->name = malloc(sizeof(char) * strlen(team_name) + 1)) == NULL)
return (NULL);
strcpy(tmp->name, team_name);
tmp->id = id;
tmp->next = teams;
return (tmp);
}
但是我需要更新列表中一个特定节点的 ID,我该怎么做? 谢谢
第 1 步:找到您要更新的列表
t_team *find_by_name(t_team *head, char *team_name)
{
t_team * tmp = head;
while(tmp != NULL){
if(strcmp(tmp->name, team_name) != 0)
head = tmp->next; //Advance the pointer to next element
else
return tmp;
}
return NULL;
}
第 2 步:更新字段
从您的主要功能调用此实用程序:-
t_team *tmp = find_by_name(head, "Some_Name");
if( tmp == NULL)
//element not found
else
tmp->id = new_id; //Update ID
更新:- 更新了 find_by_name 以使用 tmp 而不是修改 head