当前位置:网站首页>移除链表元素 <难度系数>
移除链表元素 <难度系数>
2022-04-21 08:28:00 【华为云】
1.移除链表元素 <难度系数>
题述:给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例2:
输入:head = [ ], val = 1
输出:[ ]
示例3:
输入:head = [7,7,7,7], val = 7
输出:[ ]

🧷 平台:Visual studio 2017 && windows
核心思想:
思路1,双指针,cur找到val值所在的节点,prev记录前一个位置,依次删除,细节请看下图:

思路2,新链表,把链表中所有不是val的值尾插至新链表,删除val的节点

#include<stdio.h>#include<stdlib.h>typedef int SLTDataType;struct ListNode{ int val; struct ListNode *next;};//思路1struct ListNode* removeElements1(struct ListNode* head, int val){ struct ListNode * cur = head; struct ListNode * prev = NULL; while (cur)//判断地址 { //1、相等的情况 if (cur->val == val) { if (cur == head)//1.1、第1个节点等于val时 { head = head->next; free(cur); cur = head; } else//1.2、其它节点等于val时 { prev->next = cur->next; free(cur); cur = prev->next; } } //2、不相等的情况 else { prev = cur; cur = cur->next; } } return head;}//思路2struct ListNode* removeElements2(struct ListNode* head, int val){ if(head == NULL) return NULL; //创建新节点 struct ListNode* newhead = NULL, *tail = NULL; struct ListNode* cur = head; while(cur) { struct ListNode* next = cur->next; if(cur->val == val) { free(cur); } else { if(tail == NULL) { newhead = tail = cur; } else { tail->next = cur; tail = cur; } } cur = next; } if(tail) tail->next = NULL; return newhead;}int main(){ struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode)); n1->val = 1; struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode)); n2->val = 2; struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode)); n3->val = 6; struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode)); n4->val = 3; struct ListNode* n5 = (struct ListNode*)malloc(sizeof(struct ListNode)); n5->val = 4; struct ListNode* n6 = (struct ListNode*)malloc(sizeof(struct ListNode)); n6->val = 5; struct ListNode* n7 = (struct ListNode*)malloc(sizeof(struct ListNode)); n7->val = 6; n1->next = n2; n2->next = n3; n3->next = n4; n4->next = n5; n5->next = n6; n6->next = n7; n7->next = NULL; removeElements1(n1, 6); removeElements2(n1, 6); return 0;}
版权声明
本文为[华为云]所创,转载请带上原文链接,感谢
https://bbs.huaweicloud.com/blogs/348885
边栏推荐
猜你喜欢
随机推荐
ThinkPHP quick start (III)
Ghost blank node properties
6. 堪比JMeter的.Net压测工具 - Crank 实战篇 - 收集诊断跟踪信息与如何分析瓶颈
完整版操作过程JETSON安装最新opencv
MES and ERP need to be integrated to play a key role
According to the variable name we want to visit
State Grid Enterprise standard B interface record (attachment): address code of video monitoring system
51 单片机学习_1.2 LED闪烁
TX2 安装ros-melodic opencv3.4.5 ceres1.14.0 Eigen3.3.9 gtsam cv_bridge
docker怎么访问宿主中redis服务6379端口
[reprint] explain Fourier transform in simple terms
逻辑回归----案例:癌症分类预测
八大排序(上)
autojs连接不上电脑,提示连接失败,权限不足
【转载】深入浅出的讲解傅里叶变换
pip安装成功,但是pycharm报错的问题
链表结点的删除
Experiment 1: basic operation of database
select标签 selected 选中状态动态查询
基于知名微服务框架go-micro开发gRPC应用程序


![[Nodejs]Nodejs基础学习(二)-模块机制](/img/9b/f7246550e9b021231eafaed25908d3.png)






