面试题19:删除链表(排序)中重复的节点

#include<iostream>
class Node
{
public:
	int m_pValue;
	Node* m_pNext;
	Node():m_pNext(nullptr){}
};
void deleteNode(Node* pHead)
{
	Node* pPreNode = nullptr;
	Node* pNode = pHead;
	while (pNode)
	{
		bool needDel = false;//记录节点是否可以删除
		Node* pNext = pNode->m_pNext;
		if (pNext && pNext->m_pValue == pNode->m_pValue)
			needDel = true;
		if (!needDel)
		{
			pPreNode = pNode;
			pNode = pNode->m_pNext;
		}
		else
		{
			int value = pNode->m_pValue;
			Node* needToBeDel = pNode;
			while (needToBeDel && needToBeDel->m_pValue == value)
			{//遍历可删除的节点
				pNext = needToBeDel->m_pNext;
				delete needToBeDel;
				needToBeDel = pNext;
			}
			if (pPreNode == nullptr)
				pHead = pNext;//如果慢指针为空,则表明头节点被删除
			else
				pPreNode->m_pNext = pNext;//如果慢指针不为空,则表明删除为头节点后面的节点
			pNode = pNext;//设置当前节点
		}
	}
}
发布了107 篇原创文章 · 获赞 28 · 访问量 1972

猜你喜欢

转载自blog.csdn.net/qq_38994205/article/details/104331063