删除链表中所有含有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;
    }
}
相关推荐
不穿格子的程序员1 天前
从零开始写算法——链表篇4:删除链表的倒数第 N 个结点 + 两两交换链表中的节点
数据结构·算法·链表
dragoooon341 天前
[hot100 NO.19~24]
数据结构·算法
电子硬件笔记1 天前
Python语言编程导论第七章 数据结构
开发语言·数据结构·python
Tony_yitao1 天前
15.华为OD机考 - 执行任务赚积分
数据结构·算法·华为od·algorithm
C雨后彩虹1 天前
任务总执行时长
java·数据结构·算法·华为·面试
柒.梧.1 天前
数据结构:二叉排序树构建与遍历的解析与代码实现
java·开发语言·数据结构
zhuzewennamoamtf1 天前
Linux内核platform抽象、数据结构、内核匹配机制
linux·运维·数据结构
不穿格子的程序员1 天前
从零开始写算法——链表篇5:K个一组翻转链表 + 排序链表
算法·链表·分治
自然常数e1 天前
深入理解指针(6)
c语言·数据结构·算法·visual studio
一杯美式 no sugar1 天前
数据结构——栈
c语言·数据结构·