双向链表添加节点和删除结点

双向链表添加节点和删除结点_第1张图片

以下是添加头节点的代码:

void CList::AddHead(DATA data)
{
	SNode*p = new SNode;
	p->data = data;
	if (m_pHead)
	{
		m_pHead->pPrev = p;
	}
	else {
		m_pTail = p;//链表为空第一次添加节点时候才会执行这一步
	}
	p->pPrev = nullptr;
	p->pNext = m_pHead;
	m_pHead = p;
	++m_nCount;

}

以下是添加尾节点的代码:

void CList::AddTail(DATA data)
{
	SNode*p = new SNode;
	p->data = data;
	if (m_pTail)
	{
		m_pTail->pNext = p;
	}
	else {
		m_pHead = p;//链表为空第一次添加节点时候才会执行这一步
	}
	p->pPrev = m_pTail;
	p->pNext = nullptr;
	m_pTail = p;
	++m_nCount;
}

以下是删除结点(代码多的是蠢办法,代码少的是大牛的代码):

//蠢办法
void CList::RemoveAt(POSITION p)
{
	if (m_nCount == 0)
	{
		cout << "链表里没有数据" << endl;
		return;
	}
	else if (m_nCount == 1 && (SNode*)p == m_pHead)//要删除的节点是头节点(尾节点)且链表里只有这一个
	{
		if (((SNode*)p) == m_pHead)
		{
			delete m_pHead;
			m_pHead = m_pTail = NULL;
			m_nCount = 0;
		}
		else { cout << "链表里没有要删除的数据" << endl; }
	}
	else if (m_nCount>1 && (SNode*)p==m_pHead)
	{
			m_pHead->pNext->pPrev = NULL;
			SNode*pSNod = m_pHead;
			m_pHead = m_pHead->pNext;
			delete pSNod;
	}
	else if (m_nCount>1 && (SNode*)p == m_pTail)
	{
			m_pTail->pPrev->pNext = NULL;
			SNode*pSNod = m_pTail;
			m_pTail = m_pTail->pPrev;
			delete pSNod;
	}
	else {
		POSITION pos = GetHeadPosition();
		while (pos)
		{
			if (pos == p)
			{
				((SNode*)pos)->pPrev->pNext = ((SNode*)pos)->pNext;
				((SNode*)pos)->pNext->pPrev = ((SNode*)pos)->pPrev;
				delete (SNode*)pos;
				break;
			}
			GetNext(pos);
		}
		if(!pos)
			cout<< "链表里没有要删除的数据" << endl;
	}
}
//大牛的代码
void CList::RemoveAt(POSITION pos)
{
	SNode*p = (SNode*)pos;
	if (m_pHead == p)
		m_pHead=m_pHead->pNext;//如果删除的是头节点,就把m_pHead指向下一个结点
	else 
		p->pPrev->pNext = p->pNext; //否则前一个结点指向后一个结点

	if (m_pTail == p)
		m_pTail = m_pTail->pPrev;//如果删除的是尾节点,就把m_pTail指向前一个结点
	else
		p->pNext->pPrev = p->pPrev;//否则后一个结点指向前一个结点

	delete p;
	--m_nCount;
}


你可能感兴趣的:(双向链表添加节点和删除结点)