每日一题(移除链表元素)
203. 移除链表元素 - 力扣(LeetCode)
思路一:
思路二:
思路一代码:
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode* cur = head;
struct ListNode* next = head;
struct ListNode* newhead = NULL;
struct ListNode* tail = newhead;
while(cur)
{
//满足删除条件
if(cur ->val != val)
{
//假如newnode是空
if(newhead== NULL)
{
next = cur->next;
newhead = cur;
tail = newhead;
cur = next;
}
//newnode不是空
else
{
next = cur->next;
tail->next = cur;
tail = tail->next;
cur = next;
}
}
//不满足删除条件
else
{
next = cur->next;
free(cur);
cur = next;
}
}
if(tail!=NULL)
tail->next = NULL;
return newhead;
}
思路二代码:
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode* prev=NULL;
struct ListNode* cur = head;
while(cur)
{
//节点的值满足删除条件
if(cur->val == val)
{
//当删除的是头节点
if(cur == head)
{
head = cur->next;
free(cur);
cur = head;
}
//当删除的不是头节点
else
{
prev->next = cur->next;
free(cur);
cur = prev->next;
}
}
//节点的值不满足删除条件
else//向后走
{
prev = cur;
cur=cur->next;
}
}
return head;
}
注意:以下都是针对思路一的讲解:
图解:
完结
本题的全部分析就到这里啦,若有不足,欢迎评论区指正,下期见!