c++单链表【构造函数、运算符重载、析构函数、增删查改等】

c++中的单向链表写法:实现增删查改、构造函数、运算符重载、析构函数等。

建立头文件SList.h

#pragma once

typedef int DataType;
//SList要访问SListNode,可以通过友元函数实现,友元函数在被访问的类中
class SListNode
{
	friend class SList;//友元函数
public:
	SListNode(const DataType x)
		:_data(x)
		, _next(NULL)
	{}
private:
	SListNode* _next;
	DataType _data;
};

class SList
{
public:
	SList()
		:_head(NULL)
		, _tail(NULL)
	{}
	//深拷贝
	SList(const SList& s)
		:_head(NULL)
		, _tail(NULL)
	{
		SListNode* cur = s._head;
		while (cur)
		{
			this->PushBack(cur->_data);
			cur = cur->_next;
		}
	}
	深拷贝的传统写法
	//SList& operator=(const SList& s)
	//{
	//	if (this != &s)
	//	{
	//		Clear();
	//		SListNode* cur = s._head;
	//		while (cur)
	//		{
	//			this->PushBack(cur->_data);
	//			cur = cur->_next;
	//		}
	//	}
	//	return *this;
	//}
	//深拷贝的现代写法
	SList& operator=(SList& s)
	{
		swap(_head, s._head);
		swap(_tail, s._tail);
		return *this;
	}
	~SList()
	{
		Clear();
	}
public:
	void Clear();
	void PushBack(DataType x);
	void PopBack();
	void PushFront(DataType x);
	void PopFront();
	//void Insert(size_t pos,DataType x);
	void Insert(SListNode* pos, DataType x);
	void Erase(SListNode* pos);
	SListNode* Find(DataType x);
	void PrintSList();
private:
	SListNode* _head;
	SListNode* _tail;
};

各函数的实现

#include<iostream>
using namespace std;

#include"SList.h"
#include<assert.h>

void SList::Clear()
{
	SListNode* cur = _head;
	while (cur)
	{
		SListNode* del = cur;
		cur = cur->_next;
		delete del;
   
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值