一、题目描述
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/remove-linked-list-elements
二、提供方便走读代码的图
三、题目代码
思想一:跳过head的数据,处理后面的,然后最后处理head的数据
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode* p = head;
struct ListNode* pre ;
if(p == NULL)
{
return head;
}
while(p->next!=NULL)
{
if((p->next)->val==val)
{
pre=p->next;
p->next=p->next->next;
free(pre);
}
else
{
p=p->next;
}
}
if(head->val==val)
{
pre=head;
head=head->next;
free(pre);
}
return head;
}
思路二:直接从头开始处理,分类处理
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode* p = head;
struct ListNode* pre = NULL;
while(p)
{
if(p->val==val)
{
if(p==head)
{
head=head->next;
free(p);
p=head;
}
else
{
pre->next=p->next;
free(p);
p=pre->next;
}
}
else
{
pre=p;
p=p->next;
}
}
return head;
}
四、调试代码
#include<stdio.h>
#include<stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* p = head;
struct ListNode* pre = NULL;
while (p)
{
if (p->val == val)
{
if (p == head)
{
head = head->next;
free(p);
p = head;
}
else
{
pre->next = p->next;
free(p);
p = pre->next;
}
}
else
{
pre = p;
p = p->next;
}
}
return head;
}
int main()
{
//以下面的例子为例进行调试代码
//输入:head = [7, 7, 7, 7], val = 7
//输出:[]
struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
if (n1 == NULL)return;
struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
if (n2 == NULL)return;
struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
if (n3 == NULL)return;
struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
if (n4 == NULL)return;
n1->val = 7;
n2->val = 7;
n3->val = 7;
n4->val = 7;
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = NULL;
struct ListNode* head = removeElements(n1, 7);
return 0;
}
以上是本篇文章的全部内容,如果文章有错误或者有看不懂的地方,多和喵博主交流。互相学习互相进步。如果这篇文章对你有帮助,可以给喵博主一个关注,你们的支持是我最大的动力。