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;