删除链表中所有含有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;
    }
}
相关推荐
立志成为大牛的小牛12 分钟前
数据结构——十七、线索二叉树找前驱与后继(王道408)
数据结构·笔记·学习·程序人生·考研·算法
Algo-hx15 分钟前
数据结构入门 (七):从“链接”到“分支” —— 初探树与二叉树
数据结构
小贾要学习1 小时前
【数据结构】C++实现红黑树
数据结构·c++
235162 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
周杰伦_Jay4 小时前
【Java集合体系】全面解析:架构、原理与实战选型
java·开发语言·数据结构·链表·架构
tkevinjd5 小时前
反转链表及其应用(力扣2130)
数据结构·leetcode·链表
HalvmånEver6 小时前
红黑树实现与原理剖析(上篇):核心规则与插入平衡逻辑
数据结构·c++·学习·算法·红黑树
Rubisco..9 小时前
牛客周赛 Round 111
数据结构·c++·算法
代码小菜鸡66610 小时前
java 常用的一些数据结构
java·数据结构·python
火山灿火山10 小时前
详解AVL树旋转操作实现
数据结构·c++