删除链表中所有含有val的节点

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

示例 1:

输入:head = [1,2,6,3,4,5,6], val = 6

输出:[1,2,3,4,5]

思路1:遍历查找,找到一个删一个

代码:

c 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

struct ListNode
{
	int val;
	struct ListNode* next;
};

struct ListNode* removeElements(struct ListNode* head, int val)

{
    struct ListNode* cur = head;
    struct ListNode* pre = NULL;
    while (cur != NULL)
    {
        if (cur->val == val)
        {
            if (cur == head)
            {
                head = cur->next;
                free(cur);
                cur = head;
            }
            else
            {
                pre->next = cur->next;
                free(cur);
                cur = pre->next;
            }
        }
        else
        {
            pre = cur;
            cur = cur->next;
        }

    }
    return head;
}
int main()
{
	struct ListNode* n1= (struct ListNode* )malloc(sizeof(struct ListNode));
	struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
	struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
	struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));

	n1->val = 7;
	n2->val = 6;
	n3->val = 7;
	n4->val = 6;

	n1->next = n2;
	n2->next = n3;
	n3->next = n4;
	n4->next = NULL;

	struct ListNode* head= removeElements(n1,7);

    struct ListNode* cur = head;
    while (cur)
    {
        printf("%d->", cur->val);
        cur = cur->next;
    }
    printf("NULL");

	return 0;
}

思路而,重新定义一个头节点指针=NULL;遍历链表把不等于val的节点移到新的头指针节点处,新城新的链表

代码:

c 复制代码
struct ListNode* removeElements1(struct ListNode* head, int val)
{
    struct ListNode* cur = head;
    struct ListNode* newhead = NULL;
    struct ListNode* tail = NULL;
    while (cur)
    {
        if (cur->val == val)
        {
            struct ListNode* pre = cur;
            cur = cur->next;
            free(pre);

        }
        else
        {
            if (tail == NULL)
            {
                newhead = tail = cur;
            }
            else
            {
                tail->next = cur;
                tail = tail->next;

            }
            cur = cur->next;
        }
        if(tail)
        tail->next = NULL;
    }
}
相关推荐
稚辉君.MCA_P8_Java17 分钟前
Gemini永久会员 Java动态规划
java·数据结构·leetcode·排序算法·动态规划
cookqq1 小时前
mongodb根据索引IXSCAN 查询记录流程
数据结构·数据库·sql·mongodb·nosql
ohyeah2 小时前
栈:那个“先进后出”的小可爱,其实超好用!
前端·数据结构
历程里程碑3 小时前
各种排序法大全
c语言·数据结构·笔记·算法·排序算法
树在风中摇曳3 小时前
带哨兵位的双向循环链表详解(含 C 代码)+ LeetCode138 深度解析 + 顺序表 vs 链表缓存机制对比(图解 CPU 层级)
c语言·链表·缓存
文涛是个小白呀4 小时前
Java集合大调研
java·学习·链表·面试
embrace995 小时前
【C语言学习】结构体详解
android·c语言·开发语言·数据结构·学习·算法·青少年编程
稚辉君.MCA_P8_Java5 小时前
通义 Go 语言实现的插入排序(Insertion Sort)
数据结构·后端·算法·架构·golang
稚辉君.MCA_P8_Java6 小时前
Gemini永久会员 Go 实现动态规划
数据结构·后端·算法·golang·动态规划
腾讯云开发者6 小时前
数据与 AI 双向奔赴,腾讯云架构师技术沙龙精彩回顾
数据结构