#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;
}
c++链表任意位置的插入和删除
最新推荐文章于 2023-10-25 23:08:43 发布