LeetCode 之Remove Linked List Elements

本文介绍了解决LeetCode上的移除链表元素问题的方法。该问题是要求从整数链表中移除所有值为特定数值的元素。提供了一个C语言实现的解决方案,其运行时间为12ms。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode : Remove Linked List Elements 
题目原意: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 
代码如下(leetCode 测得运行时间为12ms): 
struct ListNode *removeElements(struct ListNode *head, int val)
{
	struct ListNode *pNow  = NULL;

	while (head && head->val == val)  //!< 排除head->val == val 
	{
		head = head->next;
	}
	if (head == NULL)
	{
		return NULL;
	}

	pNow = head;
	while (pNow->next)  //!< 循环依次排除
	{
		if (pNow->next->val == val)
		{
			pNow->next = pNow->next->next;
			continue;
		}
		pNow = pNow->next;
	}

	return head;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值