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

编程入门 行业动态 更新时间:2024-10-27 22:20:12

【每日一题】<a href=https://www.elefans.com/category/jswz/34/1767470.html style=移除链表元素(C语言)"/>

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

移除链表元素,链接奉上

目录

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

思路:

正常情况:
下我们移除链表元素时,需要该位置的前结点与后节点

特别情况时:
例如

我们发现,需要改变头结点,否则因为返回的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;
}

更多推荐

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

本文发布于:2023-11-16 16:50:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628847.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:移除   元素   链表   语言

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!