博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Remove Linked List Elements
阅读量:6909 次
发布时间:2019-06-27

本文共 1289 字,大约阅读时间需要 4 分钟。

题目

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

测试用例

1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 66 --> 6 --> 1, val = 66 --> 6 --> 6, val = 61 --> 2 --> 6 --> 6 --> 6 --> 5 --> 6, val = 6

解析

这道题给出三种算法

第一种:

直接两个指针pre和cur,一前一后,相互挨着,cur指针遇到val后,pre的next直接指向cur的下一个指针,同时cur也向后移动一个。

第二种:

把指定的元素看成雷区,cur指针进入雷区后,pre停止并等待cur出雷区,同时pre的next指针指向出雷区的第一个元素。但是这种方法得有一个是否进入雷区的标志,但是我觉得可以优化。

第三种方法:

优雅的递归调用

算法实现

第一种实现:

ListNode* removeElements(ListNode* head, int val) {	ListNode *pre;	ListNode *cur;	ListNode *temp;		pre = head;	while(pre != NULL && pre->val == val)	{		temp = pre;		pre = pre->next;		delete temp;	}	if(pre == NULL)	{		return NULL;	}		head = pre;	cur = pre->next;	while(cur != NULL)	{		if(cur->val == val)		{			temp = cur;			pre->next = cur->next;			delete temp;		}		else		{			pre = cur;		}		cur = cur->next;	}//while		return head;}

第二种实现:

第三种实现:

ListNode* removeElements(ListNode* head, int val) {	ListNode *temp = NULL;	if(head && head->val == val)	{		temp = head;		head = removeElements(head->next, val);		delete temp;	}	if(head && head->next)	{		head->next = removeElements(head->next, val);	}	return head;}

  

 

转载于:https://www.cnblogs.com/stemon/p/4475168.html

你可能感兴趣的文章
禁止 centos 休眠
查看>>
列表删除页代码
查看>>
亚马逊的EC2云计算系统
查看>>
分别让div浮层靠左靠右和居中
查看>>
如何解决 JMeter 通过 JDBC 访问 Oracle 和 MySQL 的问题 (留言中有 Test Plan 实例下载)...
查看>>
19.7 主动模式和被动模式;19.8 添加监控主机;19.9 添加自定义模板19.10处理图形中的...
查看>>
SCOM2012功能测试(14)—创建.NET应用程序性能监控
查看>>
我的友情链接
查看>>
IEnumerable和IEnumerable<T>接口
查看>>
重定向redirect与跳转forward区别
查看>>
CentOS7之Rsync+Inotify架构实现实时同步文件和文件夹
查看>>
linux日志管理
查看>>
A.约数个数的和
查看>>
BZOJ1041:[HAOI2008]圆上的整点(数论)
查看>>
c# small tips
查看>>
双色球
查看>>
git 添加tab补全
查看>>
web.xml配置
查看>>
Leetcode 67 二进制求和
查看>>
素数判断的多种方法
查看>>