描述

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

分析

先构造一个链表结点dummyHead,并让这个结点“插到”原链表头结点之前。举个例子:假设原链表是

1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6

通过dummyHead->next=head让原链表前多了这个结点,以方便操作:

INT_MIN --> 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6

再用一个指针cur指向这个新的链表的头结点,每次做如下操作:

  • cur是否为空?若为空,退出循环,否则进入下一步;
  • cur->next是否为空?若为空,说明已遍历完链表,令cur=cur->next,退出循环;否则,继续判断cur->next->val是否等于给定的值val,若不相等,则遍历下一元素,即令cur=cur->next。若相等,说明找到该元素,进行删除结点操作。
  • 为了删除当前结点,需要用一个临时结点tmp指向该结点,然后让cur“跳过”该结点,跳过后,删除该结点,否则会造成内存泄漏。删除操作结束后,继续下一次循环。

代码如下:

/**
* 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) {
ListNode* dummyHead = new ListNode(INT_MIN); //create a node as "new head"
dummyHead -> next = head;
ListNode* cur = dummyHead;
while(cur){
if(cur -> next && cur -> next -> val == val){ //be sure of that cur -> next is valid
ListNode* tmp = cur -> next; //store the node we want to delete
cur -> next = tmp -> next;
delete tmp; //delete the node or it may cause memory leak
}else
cur = cur -> next; //otherwise modify cur
}
return dummyHead -> next;
}
};

最新文章

  1. spring 多数据源一致性事务方案
  2. HttpClient通过Post上传多个文件
  3. HTML5开发笔记:初窥CANVAS,上传canvas图片到服务器
  4. 【android design】android常用设计资源
  5. 10个TWaver 网页3D可视化精彩案例
  6. C语言资源
  7. Android 依赖注入 ButterKnife 基本使用
  8. Oracle恢复已删除数据
  9. 关于NSLocalizedString(@"Foo %@",nil)
  10. 百度云推送的Java实现
  11. Week2(9月19日):增加一个CodeFirst的例子来说明
  12. Java迭代器Iterator
  13. linux数据库常用指令
  14. Linux命令之tar-rsync
  15. tomcat生命周期的管理——生命周期统一接口Lifecycle
  16. Mysql外键约束--转载
  17. 带着新人学springboot的应用12(springboot+Dubbo+Zookeeper 下)
  18. 解决移动端真机不能下拉滚动bug
  19. nginx 日志切割脚本
  20. node学习: package.json

热门文章

  1. Scratch编程:贪吃鱼(十一)
  2. [CF896C]Willem, Chtholly and Seniorious
  3. HA 高可用集群概述及其原理解析
  4. React 了解学习
  5. ITIL《信息技术基础架构库》
  6. 8 search中的timeout参数
  7. OO——UML解析
  8. Redis相关概念
  9. 从Iterator到async/await
  10. Struts框架笔记03_OGNL表达式与值栈