现在的位置: 首页 > 综合 > 正文

Remove duplicates from sorted list II

2017年12月23日 ⁄ 综合 ⁄ 共 473字 ⁄ 字号 评论关闭

题目比较简单,就是用两个指针每次标识一个固定值的头和尾,如果只有一个则添加否则全删除。

 

ln* deleteDuplicates(ln* head)
{
	if (!head || !head->next)
		return head;

	ln* pHead=NULL;
	ln* pTail=pHead;
	ln* pPre=head;
	
	while(pPre)
	{
		ln* pNext=pPre;
		while(pNext&&pNext->val==pPre->val)
			pNext=pNext->next;
		if (pPre->next==pNext)
		{
			if (pHead==NULL)
			{
				pHead=pTail=pPre;
				pPre=pPre->next;
			}
			else
			{
				pTail->next=pPre;
				pTail=pTail->next;
				pPre=pPre->next;
			}
		}
		else
		{
			while(pPre!=pNext)
			{
				ln* tmp=pPre->next;
				delete pPre;
				pPre=tmp;
			}
			pPre=pNext;
		}
	}
	if (pTail)
		pTail->next=NULL;
	return pHead;
}

 

抱歉!评论已关闭.