203.移除链表元素
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
示例 1: 输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
示例 2: 输入:head = [], val = 1 输出:[]
示例 3: 输入:head = [7,7,7,7], val = 7 输出:[]
思路:
如果头节点需要删除的话,需要单独写一部分删除头结点的代码逻辑。
或者把malloc一个新的节点,设置为头节点。这样的话就不需要分情况操作了。——虚拟头节点。
直接使用原来的链表来进行移除节点操作:
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* cur;
struct ListNode* temp;
// 注意这里不是if
while (head != NULL && head->val == val) {
temp=head;
head=head->next;
free(temp);
}
cur=head;
//因为要操作两个节点,所以这两个节点都不能为空
while (cur&&cur->next) {
if(cur->next->val==val){
temp=cur->next;
cur->next=cur->next->next;
free(temp);
}
else {
cur=cur->next;
}
}
return head;
}
设置一个虚拟头结点在进行移除节点操作:
struct ListNode* removeElements(struct ListNode* head, int val){
typedef struct ListNode ListNode;
ListNode *shead;
shead = (ListNode *)malloc(sizeof(ListNode));
shead->next = head;
ListNode *cur = shead;
while(cur->next != NULL){
if (cur->next->val == val){
ListNode *tmp = cur->next;
cur->next = cur->next->next;
free(tmp);
}
else{
cur = cur->next;
}
}
head = shead->next;
free(shead);
return head;
}
这一期专栏记录将我每天的刷题,希望各位的监督,也希望和各位共勉。
追光的人,终会光芒万丈!!