LeetCode 之Remove Linked List Elements

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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章