[LeetCode] Remove Linked List Elements
2015-10-22 17:45
381 查看
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.
每次遇到链表操作,树操作的时候我的大脑就会messed up. 各种考虑不周全,各种edge case 失败。
思路分两步,第一步删除头,即比如要删除6,而链表是6->6->3->2。先把以目标6开头的链表变成不已目标开头的链表。
第二步就便利链表,如果发现next 是目标,就把当前的next 变为next->next。
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.
每次遇到链表操作,树操作的时候我的大脑就会messed up. 各种考虑不周全,各种edge case 失败。
思路分两步,第一步删除头,即比如要删除6,而链表是6->6->3->2。先把以目标6开头的链表变成不已目标开头的链表。
第二步就便利链表,如果发现next 是目标,就把当前的next 变为next->next。
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode* p = NULL; while (head != NULL && head->val == val) { head = head->next; } if (head == NULL) return NULL; p = head; while (p != NULL) { if (p->next != NULL && p->next->val == val) { p->next = p->next->next; } else { p = p->next; } } return head; }
相关文章推荐
- 【JSON】Jackson初学,及常用的例子
- Flume之Failover和Load balancing原理及实例
- Hibernate无法创建表的原因分析
- error: RPC failed; result=18, HTTP code = 200 gitlab 百兆以上库下载报错
- 在Unity世界里遇到的第一个错误!
- 可视化学习之百度echarts工具(2)
- Flash动画分类
- gm: error while loading shared libraries: libpng15.so.15: cannot open shared object file: No such file or directory
- VMware扩展磁盘大小
- 写作的意境
- 设计模式之观察者模式(订阅模式),jquery实现
- 今天在做一个SSH整合测验时发现了一个异常(According to TLD or attribute directive in tag file)
- Andorid 布局layout_margin和padding分析
- Hibernate-配置文件-hibernate.cfg.xml
- IPC$使用教程
- AES加密和解密
- js动态删除增加dom元素
- windows git 环境搭建
- Linux常用的查找命令总结
- ajax 项目实例