LeetCode(203) Remove LinkedList Elements
2024-10-12 10:00:15
题目
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
分析
删除链表中的指定值的节点。
需要注意的是,所需要删除节点的位置,头,中间,尾,不同位置需要不同处理,避免断链~
AC代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == NULL)
return head;
ListNode *pre = head, *p = head;
while (p)
{
//找到要删除的节点元素
if (p->val == val)
{
//判断当前节点为头结点
if (p == head)
{
head = p->next;
ListNode *q = p;
//更新头
p = head;
pre = head;
delete q;
q = NULL;
}
//删除尾节点
else if (p->next == NULL)
{
pre->next = NULL;
delete p;
p = NULL;
}
//删除链表中间节点
else{
pre->next = p->next;
ListNode *q = p;
p = p->next;
delete q;
q = NULL;
}//else
}//if
else{
pre = p;
p = p->next;
}
}//while
return head;
}
};
最新文章
- System.Data.OleDb.OleDbException: 未指定的错误的解决方法
- 使用Prism6 建立 Windows 10 通用程序.
- (期望)A Dangerous Maze(Light OJ 1027)
- MapReduce应用案例--单表关联
- Codeforces #369 div2 D.Directed Roads
- 反射中通过class标记来获取字段及方法
- poj 2528 线段树 离散化的小技巧
- GUI(图形用户界面)
- failure injection
- VS2008 动态库和静态库的生成和加载
- 在Linux Mint13下编译安装mono运行时
- LeetCode-Maximum Subarray[dp]
- easyui-combobox的option选项为true与false时的问题
- nagios安装check_linux_stats.pl插件报错Can't locate Sys/Statistics/Linux.pm in @INC的处理?
- python 取整
- PyQt 5.4参考指南 ---- PyQt5和PyQt4之间的差异
- Java从零开始学三(public class和class)
- C# WinForm实现任务栏程序图标闪烁
- 海康ipc onvif抓包分析
- Hibernate的HQL中in参数设置
热门文章
- NET Core实现OAuth2.0的ResourceOwnerPassword和ClientCredentials模式
- HDU 1114 Piggy-Bank 完全背包 dp
- OpenCV图像处理之 Mat 介绍
- 【0 基础学Dojo】第【1】篇 HelloWord
- SQL Server事务的四种隔离级别
- nodejs 实践:express 最佳实践(五) connect解析
- Mysql系列常见面试题(三)
- Linux系统常用命令大全
- 【TensorFlow入门完全指南】模型篇·最近邻模型
- python爬虫之路——初识函数与控制语句