代码如下所示:
#include <iostream>
using namespace std;
struct ListNode{
int m_nValue;
ListNode *m_pNext;
};
class List{
public:
List(){
pHead = nullptr;
}
void showList();//打印链表
void AddToTail(int value);//尾部添加节点
void RemoveNode(int value); //删除节点
private:
ListNode *pHead;
};
int main()
{
List MyList;
MyList.AddToTail(10);
MyList.AddToTail(5);
MyList.AddToTail(7);
MyList.AddToTail(13);
MyList.AddToTail(22);
MyList.AddToTail(17);
MyList.showList();
MyList.RemoveNode(5);
MyList.showList();
MyList.RemoveNode(13);
MyList.showList();
MyList.RemoveNode(17);
MyList.showList();
return 0;
}
void List::showList(){
ListNode *cur = pHead;
while(cur != nullptr){
cout<<cur->m_nValue<<" ";
cur = cur->m_pNext;
}
cout<<endl;
}
void List::RemoveNode(int value){
if(pHead == nullptr)
return;
ListNode *pre = pHead;
if(pHead->m_nValue == value){
pHead = pHead->m_pNext;
delete pre;
pre = nullptr;
return;
}
else{
ListNode *next = pre->m_pNext;
while(next != nullptr){
if(next->m_nValue == value){
pre->m_pNext = next->m_pNext;
delete next;
next = nullptr;
return;
}
pre = next;
next = next->m_pNext;
}
}
}
void List::AddToTail(int value){
ListNode *pNew = new ListNode;
pNew->m_nValue = value;
pNew->m_pNext = nullptr;
if(pHead == nullptr){
pHead = pNew;
return;
}
ListNode *node = pHead;
while(node->m_pNext != nullptr){
node = node->m_pNext;
}
node->m_pNext = pNew;
}
运行结果如下: