题目

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;
}
};

GitHub测试程序源码

最新文章

  1. System.Data.OleDb.OleDbException: 未指定的错误的解决方法
  2. 使用Prism6 建立 Windows 10 通用程序.
  3. (期望)A Dangerous Maze(Light OJ 1027)
  4. MapReduce应用案例--单表关联
  5. Codeforces #369 div2 D.Directed Roads
  6. 反射中通过class标记来获取字段及方法
  7. poj 2528 线段树 离散化的小技巧
  8. GUI(图形用户界面)
  9. failure injection
  10. VS2008 动态库和静态库的生成和加载
  11. 在Linux Mint13下编译安装mono运行时
  12. LeetCode-Maximum Subarray[dp]
  13. easyui-combobox的option选项为true与false时的问题
  14. nagios安装check_linux_stats.pl插件报错Can't locate Sys/Statistics/Linux.pm in @INC的处理?
  15. python 取整
  16. PyQt 5.4参考指南 ---- PyQt5和PyQt4之间的差异
  17. Java从零开始学三(public class和class)
  18. C# WinForm实现任务栏程序图标闪烁
  19. 海康ipc onvif抓包分析
  20. Hibernate的HQL中in参数设置

热门文章

  1. NET Core实现OAuth2.0的ResourceOwnerPassword和ClientCredentials模式
  2. HDU 1114 Piggy-Bank 完全背包 dp
  3. OpenCV图像处理之 Mat 介绍
  4. 【0 基础学Dojo】第【1】篇 HelloWord
  5. SQL Server事务的四种隔离级别
  6. nodejs 实践:express 最佳实践(五) connect解析
  7. Mysql系列常见面试题(三)
  8. Linux系统常用命令大全
  9. 【TensorFlow入门完全指南】模型篇·最近邻模型
  10. python爬虫之路——初识函数与控制语句