Easy-题目51:203. Remove Linked List Elements
2016-05-30 20:50
459 查看
题目原文:
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
题目大意:
删除单链表中指定节点。
题目分析:
用两个指针p和q(p始终是q前驱节点)并行向后推,若找到q是待删除节点(q->val==val)则删除q,但还没有处理头结点,故看一下head->val与val是否相等。
源码:(language:cpp)
成绩:
32ms,beats 54.36%,众数36ms,45.72%.
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
题目大意:
删除单链表中指定节点。
题目分析:
用两个指针p和q(p始终是q前驱节点)并行向后推,若找到q是待删除节点(q->val==val)则删除q,但还没有处理头结点,故看一下head->val与val是否相等。
源码:(language:cpp)
class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode *p=head; if(!p || (!p->next && p->val==val))//p is null or (length of linklist=1 and this unique node is going to be deleted) return NULL; else { ListNode *q=head->next; while(q) { if(q->val==val) {// the first node is going to be deleted p->next=p->next->next; q=q->next; continue; } else { p=p->next; q=q->next; } } if(head->val!=val) return head; else return head->next; } } };
成绩:
32ms,beats 54.36%,众数36ms,45.72%.
相关文章推荐
- hdu 5664 Lady CA and the graph (树分治,树状数组)
- 第十三周项目1:阅读、修改和运行关于交通工具类的程序(3)
- poj 3378 pascal
- JAVA学习笔记整理三(抽象类、接口、匿名类)
- java的动态代理机制详解 动态代理类
- 【记账小助手】项目文档(包含需要用到的知识点)
- 安卓深度探索(卷一)第八章
- Oracle 注入技巧收集
- MySQL配置文件my.cnf参数优化和中文详解
- 2016SDAU课程练习三1016
- RAID磁盘阵列
- shell(四)
- 操作系统——进程管理
- 软件工程课程建议
- 安卓深度探索(卷一)第七章
- 安卓深度探索(卷一)第六章
- 断点下载
- LDAP简单介绍
- JavaScript JSON 学习笔记
- LSM-tree 一种高效的索引数据结构