当前位置:首页 > 编程笔记 > 正文
已解决

【每日一题】移除链表元素(C语言)

来自网友在路上 173873提问 提问时间:2023-11-05 05:25:10阅读次数: 73

最佳答案 问答题库738位专家为你答疑解惑

移除链表元素,链接奉上
在这里插入图片描述

目录

  • 思路:
  • 代码实现:
  • 链表题目小技巧:

思路:

正常情况:
下我们移除链表元素时,需要该位置的前结点与后节点
在这里插入图片描述
特别情况时:
例如在这里插入图片描述

我们发现,需要改变头结点,否则因为返回的head因为指向的位置被free,会导致程序错误

代码实现:

struct ListNode* removeElements(struct ListNode* head, int val) 
{struct ListNode* prev = NULL;struct ListNode* cur = head;while(cur)//当cur为NULL时自动结束{if(cur->val == val)//分别判断cur->val的情况{struct ListNode* next = cur->next;free(cur);if(!prev){//当prev为NULL时改变headhead = next;}else{prev->next = next;}cur = next;}else{prev = cur;cur = cur->next;}}return head;
}

链表题目小技巧:

我们调试时可以在VS或其他的软件进行调试,也不用专门搞一个链表:
可以创建一个如下的main函数,根据题目要求进行调试

int main()
{struct ListNode* n1 = (ListNode*)malloc(sizeof(ListNode));struct ListNode* n2 = (ListNode*)malloc(sizeof(ListNode));struct ListNode* n3 = (ListNode*)malloc(sizeof(ListNode));struct ListNode* n4 = (ListNode*)malloc(sizeof(ListNode));struct ListNode* n5 = (ListNode*)malloc(sizeof(ListNode));if (!(n1 && n2 && n3 && n4 && n5)){perror("malloc");return -1;}n1->next = n2;n2->next = n3;n3->next = n4;n4->next = n5;n5->next = NULL;n1->val = 1;n2->val = 2;n3->val = 3;n4->val = 4;n5->val = 5;return 0;
}
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"【每日一题】移除链表元素(C语言)":http://eshow365.cn/6-32449-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!