c++链表任意位置的插入和删除

#include<iostream>
#include<assert.h>
using namespace std;
struct ListNode
{
	ListNode(int data)
		:_pNext(nullptr)
		,_data(data)
	{}
	ListNode* _pNext;
	int _data;
};
ListNode* FindListNode(ListNode*& pHead, int data) {
	assert(pHead);
	ListNode* pCur = pHead;
	while (pCur) {
		if (pCur->_data == data) {
			return pCur;
		}
		pCur = pCur->_pNext;
	}
	return nullptr;
}
void Insert( ListNode* pos,int data) {
	if (pos == nullptr) {
		return;
	}
	ListNode* pNewNode = new ListNode(data);
	pNewNode->_pNext = pos->_pNext;
	pos->_pNext = pNewNode;
}
void Erase(ListNode*& pHead,ListNode* pos) {
	if (pos == nullptr || pHead == nullptr) {
		return;
	}
	if (pos == pHead) {
		pHead = pos->_pNext;
	}
	else {
		ListNode* pre = pHead;
		while (pre&&pre->_pNext!=pos) {
			pre = pre->_pNext;
			
		}
		if (pre) {
			pre->_pNext = pos->_pNext;
		}
	}

}
void PushBack(ListNode*& pHead,int data) {
	if (pHead == nullptr) {
		pHead = new ListNode(data);

	}
	else {
		ListNode* pCur = pHead;
		while (pCur->_pNext) {
			pCur = pCur->_pNext;
		}
		pCur->_pNext = new ListNode(data);

	}
	
		
	
}
void Print(ListNode*& pHead) {
	ListNode* pCur = pHead;
	while (pCur) {
		cout << pCur->_data << " ->";
		pCur = pCur->_pNext;

	}
	cout << "NULL" << endl;
}
int main() {
	ListNode* p=nullptr;
	PushBack(p, 1);
	PushBack(p, 2);
	PushBack(p, 3);
	PushBack(p, 4);
	PushBack(p, 5);
	Insert(FindListNode(p,5), 6);
	Print(p);
	Erase(p,FindListNode(p, 5));
	Print(p);
	Erase(p, FindListNode(p, 1));
	Print(p);



	system("pause");
	return 0;
}
发布了78 篇原创文章 · 获赞 10 · 访问量 3840

猜你喜欢

转载自blog.csdn.net/weixin_44374280/article/details/101949999
今日推荐