c - 如何从C中的链表中删除特定节点?
问题描述
以下代码从列表中删除特定整数,但我想删除一个 char 数组。任何人都可以帮助我如何修改此代码,以便它删除一个 char arr[]
void removeSpecific(int delValue)
{
struct node *temp1 = head; //temp1 Keeps track of the current node
struct node *temp2 = NULL; //temp2 Keeps tract of the previous node
if(temp1->num == delValue) //Special case: If the item is in the start node
{
struct node *temp3 = head;
head=head->next;
free(temp3);
}
else
{
while(temp1->num != delValue) //If the number is not present in the current node
{ // we move to the next node
if(temp1 -> next == NULL)
{
printf("\nGiven node not found in the list!!!");
exit(1);
}
temp2 = temp1; // Add of 6 next -> 8 ->next ------- 9
temp1 = temp1 -> next; // temp1 - Add of 8
}
temp2 -> next = temp1 -> next; // removing the node
free(temp1);
free(temp2);
printf("\nOne node deleted!!!\n\n");
}
}
解决方案
如果要删除 num 为 a 的 struc ,char[]
针为 a char *
,您可以使用strcmp
在删除第一个元素的情况下,我将消息移出 else 以获取它
void removeSpecific(const char* delValue)
{
struct node *curr = head;
struct node *prev = NULL;
if(!strcmp(curr->num, delValue))
{
struct node *tmp = head;
head=head->next;
free(tmp);
} else {
while(strcmp(curr->num, delValue)) {
if(curr -> next == NULL)
{
printf("\nGiven node not found in the list!!!");
exit(1);
}
prev = curr;
curr = curr -> next;
}
prev -> next = curr -> next; // removing the node
free(curr);
}
printf("\nOne node deleted!!!\n\n");
}
推荐阅读
- c++ - 问题 19 项目欧拉计数星期日
- javascript - 无法让 AJAX 提交工作以更新 post_content
- yii2 - 如何配置 Yii2 UrlManager 以处理带有和不带有斜杠的规则
- google-sheets - 在表格中使用查询导入范围时如何显示个性化消息
- python - 如何将带有 for、if、elif 的列表追加转换为列表理解
- javascript - 无法读取属性“innerHTML”
- javascript - Node.js 注销 Steam 机器人
- javascript - 如何用js移动元素的x/y位置?
- javascript - 如何使用 Promise 来返回这个未来值?
- typescript - tsconfig 中不包含 tests/** 时,VScode TS 语言功能不可用