删除链表中所有含有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;
    }
}
相关推荐
拓人间精准客6 分钟前
ToB 销售获客避坑指南:如何用全维度大数据实现降本增效
大数据·数据结构·单例模式
小七在进步35 分钟前
数据结构:快速排序
数据结构·算法·排序算法
lzx_0021 小时前
list(全)
数据结构·list
不灭的黄金瞳12316 小时前
C语言手写顺序表
c语言·开发语言·数据结构
qeen8717 小时前
【数据结构】哈希表的C++实现与封装
数据结构·c++·散列表·哈希表
重生之后端学习17 小时前
239. 滑动窗口最大值[困难]✅
java·数据结构·算法·leetcode·职场和发展
fpcc18 小时前
算法和数据结构—动态规划法
数据结构·算法·动态规划
星星.72220 小时前
C++算法竞赛|二分查找与二分答案:边界模板、浮点二分、STL
数据结构·c++·算法
动词ing20 小时前
【学习笔记】数据结构(数组长度和关键特性+快慢指针+左右指针)
数据结构·笔记·学习
linux-hzh1 天前
百日算法修炼 · Day 17
数据结构·算法