lintcode(E) 删除链表中的元素
来源:互联网 发布:java开发工程师是什么 编辑:程序博客网 时间:2024/05/07 14:49
删除链表中的元素
描述
笔记
数据
评测
删除链表中等于给定值val的所有节点。
您在真实的面试中是否遇到过这个题? Yes
样例
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
最开始我的代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: /** * @param head a ListNode * @param val an integer * @return a ListNode */ ListNode *removeElements(ListNode *head, int val) { // Write your code here if(head==NULL) return NULL; ListNode* pre; pre->next=head; ListNode* p=pre; while(p->next){ if(p->next->val==val){ ListNode *q=p->next; if(q->next) p->next=q->next; free(q); } } return pre->next; }};
然后通过率18%,
错误点:if(q->next)
这个判断没有必要,链表是1->2->3->null;
之前加这个判断,是想着,如果要删除3这个结点的话,null后面没有后继,但是删除3后,自然不会循环下去,如果加了这个判断,直接删了3结点
另外一个点是pre应该new ListNode(X),这个我知道,但是我没有。。。
还有就是c和C++搞混
正确版
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: /** * @param head a ListNode * @param val an integer * @return a ListNode */ ListNode *removeElements(ListNode *head, int val) { // Write your code here ListNode* pre=new ListNode(-1); pre->next=head; ListNode* p=pre; while(p->next){ if(p->next->val==val){ ListNode *q=p->next; p->next=q->next; q->next=NULL; delete q; } else p=p->next; } return pre->next; }};
0 0
- lintcode(E) 删除链表中的元素
- LintCode-删除链表中的元素
- LintCode之删除链表中的元素
- 【Lintcode】删除链表中的元素
- LintCode 452 删除链表中的元素
- LintCode【入门】删除链表中的元素
- lintcode-入门-删除链表中的元素
- LintCode 删除链表中的元素
- LintCode 删除链表中的元素
- 删除链表中的元素-LintCode
- Lintcode 452.删除链表中的元素
- lintcode 452 删除链表中的元素
- LintCode : 删除链表中的重复元素
- [LintCode]452.删除链表中的元素
- LintCode 删除链表中的元素
- [lintcode]-链表 删除链表中的元素
- LintCode:删除链表中的元素452
- Lintcode删除链表中的元素
- nyoj 大数阶乘
- Dlib库中实现正脸人脸检测的测试代码
- 在html页面上内容竖着显示
- NYOJ 823 人形序列
- 博为峰Java技术题 ——JavaSE 泛型Ⅱ
- lintcode(E) 删除链表中的元素
- jdbc创建步骤
- eclipse 项目提示"Project facet Java version 1.8 is not supported"
- python读入中文文本编码错误
- MVC , MVP ,MVVM 的区别
- MyBatis使用遇到的问题
- JAVA开发工具类
- C++14学习笔记(6)——两个使数值字面值更易读的特性
- PHP随机生成字符串