链表常用函数

链表的常用操作包括:

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);
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值