茂名网站制作策划,预约网站如何自己做,中国住房和城乡建设部网站注册中心,vue.js网站如果做自适应移除链表元素#xff0c;链接奉上 目录 思路#xff1a;代码实现#xff1a;链表题目小技巧#xff1a; 思路#xff1a;
在正常情况#xff1a; 下我们移除链表元素时#xff0c;需要该位置的前结点与后节点#xff0c; 在特别情况时#xff1a; 例如
我们发现链接奉上 目录 思路代码实现链表题目小技巧 思路
在正常情况 下我们移除链表元素时需要该位置的前结点与后节点 在特别情况时 例如
我们发现需要改变头结点否则因为返回的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;
}