LeeCode-Remove Linked List Elements
2016-04-26 20:44
190 查看
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val)
{
if(head==NULL)
return NULL;
if(head->next==NULL&&head->val==val)
{
return NULL;
}
if(head->next==NULL&&head->val!=val)
{
return head;
}
struct ListNode *p=head;
while(p->val==val&&p->next!=NULL)
{
p=p->next;
}
if(p->val==val)
{
return NULL;
}
head=p;
if(p->next==NULL)
{
return head;
}
while(p->next->next!=NULL)
{
if(p->next->val==val)
{
p->next=p->next->next;
continue;
}
p=p->next;
}
if(p->next->val==val)
{
p->next=NULL;
}
return head;
}
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val)
{
if(head==NULL)
return NULL;
if(head->next==NULL&&head->val==val)
{
return NULL;
}
if(head->next==NULL&&head->val!=val)
{
return head;
}
struct ListNode *p=head;
while(p->val==val&&p->next!=NULL)
{
p=p->next;
}
if(p->val==val)
{
return NULL;
}
head=p;
if(p->next==NULL)
{
return head;
}
while(p->next->next!=NULL)
{
if(p->next->val==val)
{
p->next=p->next->next;
continue;
}
p=p->next;
}
if(p->next->val==val)
{
p->next=NULL;
}
return head;
}
相关文章推荐
- 山东省第五届ACM省赛题——Circle(递推求概率)
- LeeCode-Pow(x, n)
- 学习JAVA一
- HTML 表单(form) 详解
- YEOMAN知识点整理及翻译
- 前端-踩过的坑
- 证书分享给别的电脑用
- 拦截/监听器 —— Filter、Interceptor、Listener
- HDU 1335 (16进制以下)把m进制转换为n进制
- Problem-M
- 100行PHP代码实现socks5代理服务器
- RxJS入门(3)----深入Sequence
- 【opencv学习】之split函数提取多通道图像的单通道图像
- 微信JS-SDK说明文档---自己总结了config时的参数获取方式
- 从一个Activity直接跳转到一个Fragment中,进行相应的操作
- HTML5开发中ping标签的用法及隐私追踪
- PHP的图片处理类(缩放、加图片水印和剪裁)
- java中使用反射做一个工具类,来为指定类中的成员变量进行赋值操作,使用与多个类对象的成员变量的赋值。
- Eclipse下如何运行微信SDK_Demo
- Android四大组件之一——Broadcast Receiver