链表的常用操作包括:
1. 插入(依序插入链尾)
2. 查找
3. 删除
4. 打印输出
5. 判空
源代码如下:
MyList.h
#include <iostream>
struct ListNode
{
int nData;
ListNode* pNext;
};
class MyList
{
public:
MyList() : m_pHead(NULL) {}
void Insert(int data); // 直接在尾部插入
bool Find(int data);
void Delete(int data);
void Print(); //
bool Empty();
private:
ListNode* m_pHead;
};
MyList.cpp
#include "MyList.h"
#include <iostream>
using namespace std;
void MyList::Insert(int data)
{
ListNode* pNew = new ListNode;
pNew->nData = data;
pNew->pNext = NULL;
if (NULL == m_pHead)
{
m_pHead = pNew;
return;
}
ListNode* pCur = m_pHead;
while (pCur->pNext != NULL)
pCur = pCur->pNext;
pCur->pNext = pNew;
}
bool MyList::Find(int data)
{
ListNode* pCur = m_pHead;
while (pCur != NULL)
{
if (pCur->nData == data)
return true;
pCur = pCur->pNext;
}
return false;
}
void MyList::Delete(int data)
{
if (NULL == m_pHead)
return;
if (m_pHead->nData == data)
{
ListNode* pDelete = m_pHead;
m_pHead = m_pHead->pNext;
delete pDelete;
return;
}
ListNode* pPrev = m_pHead;
ListNode* pCur = m_pHead->pNext;
while (pCur != NULL)
{
if (pCur->nData == data)
{
pPrev->pNext = pCur->pNext;
delete pCur;
return;
}
pCur = pCur->pNext;
pPrev = pPrev->pNext;
}
}
void MyList::Print()
{
ListNode* pCur = m_pHead;
while (pCur != NULL)
{
std::cout << pCur->nData << " ";
pCur = pCur->pNext;
}
std::cout << std::endl;
}
bool MyList::Empty()
{
return (m_pHead == NULL);
}