删除链表中所有含有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;
    }
}
相关推荐
yb0os17 分钟前
RPC实战和核心原理学习(一)----基础
java·开发语言·网络·数据结构·学习·计算机·rpc
hope_wisdom1 小时前
C/C++数据结构之栈基础
c语言·数据结构·c++··stack
野犬寒鸦2 小时前
力扣hot100:环形链表(快慢指针法)(141)
java·数据结构·算法·leetcode·面试·职场和发展
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 38: 二叉树的锯齿形层序遍历、二叉树最大宽度
java·linux·运维·算法·leetcode·链表·职场和发展
宁檬精4 小时前
算法练习——55.跳跃游戏
数据结构·算法·游戏
高山有多高6 小时前
顺序表:数据结构中的基础线性存储结构
数据结构
默默无名的大学生6 小时前
数据结构——链表的基本操作
数据结构·算法
_OP_CHEN6 小时前
数据结构(C语言篇):(十一)二叉树概念介绍
c语言·开发语言·数据结构·二叉树·学习笔记··
Neverfadeaway6 小时前
C语言————冒泡排序(例题2)
c语言·数据结构·算法·冒泡排序·升序排列·降序排列
散1126 小时前
01数据结构-B树
数据结构·b树