电商网站建设网,东莞阿里网站设计,网站信息平台建设方案,福建省第二电力建设公司网站1.删除链表中等于给定值 val 的所有节点 题目来源 给你一个链表的头节点 head 和一个整数 val #xff0c;请你删除链表中所有满足 Node.val val 的节点#xff0c;并返回 新的头节点 。
/*** Definition for singly-linked list.* struct ListNode {* int val;* s…1.删除链表中等于给定值 val 的所有节点 题目来源 给你一个链表的头节点 head 和一个整数 val 请你删除链表中所有满足 Node.val val 的节点并返回 新的头节点 。
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/struct ListNode* removeElements(struct ListNode* head, int val){struct ListNode* cur NULL;struct ListNode* tail head;while(tail!NULL){if(tail-val val){//删除1、头部删除 2、中间删除//特例[7 7 7 7 7] 7if(tail head){head tail-next;free(tail);tail head;}else{cur-next tail-next;free(tail);tail cur-next;}}else{cur tail;tail tail-next;}}return head;
}/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/struct ListNode* removeElements(struct ListNode* head, int val){struct ListNode* cur head;struct ListNode* newhead NULL;struct ListNode* end NULL;// [1,2,6,3,4,5,6]// 6while(cur!NULL){if(cur-val val){struct ListNode* nowhead cur;cur cur-next;free(nowhead);}else{if(end NULL){newhead end cur;// 1 2 }else{end-next cur;end end-next;}cur cur - next;// end-next NULL; 在这里置空}}// 或者在这里置空if(end)// []end-next NULL;return newhead;
}