C++实现单链表
SList.h
#include<iostream>
#include<assert.h>
using namespace std;
typedef int DataType;
struct Node
{
DataType data;
struct Node* next;
};
class SList
{
public:
SList() :head(nullptr) {}
SList(const SList& sl) { head = copySList(sl); }
SList& operator=(const SList& sl)
{
Node* p = copySList(sl);
free();
head = p;
return *this;
}
~SList() { free(); }
public:
void push_back(const DataType&);
void push_front(const DataType&);
void pop_back();
void pop_front();
void print()const;
Node* find(const DataType&); // 以某值为索引,查找某节点
void insert(Node* p, const DataType&); // 在p结点之后插入一个值
void erase(Node* p); // 删除p结点
private:
Node* head;
void free()
{
while (head != nullptr)
{
Node* next = head->next;
delete head;
head = next;
}
head = nullptr;
}
Node* copySList(const SList& sl)
{
//SList newsl;
//Node* cur = sl.head;
//while (cur != NULL)
//{
// newsl.push_back(cur->data);
// cur = cur->next;
//}
//return newsl.head;
Node ret{ 0,NULL };
Node* node = &ret;
Node* cur = sl.head;
while (cur != NULL)
{
Node* tmp = new Node{ cur->data,NULL };
node->next = tmp;
node = node->next;
cur = cur->next;
}
return ret.next;
}
Node* CreatNode(const DataType& x)
{
Node* newnode = new Node{ x, nullptr };
//newnode->data = x;
//newnode->next = nullptr;
return newnode;
}
};
SList.cpp
#include"SList.h"
void SList

本文介绍了如何使用C++和C语言实现无头结点的单链表,重点讨论了C++中私有成员函数copySList在拷贝构造和赋值操作中的应用,以及无头单链表在存储和删除操作上的特点。单链表虽然头插头删高效,但尾部操作和中间元素操作复杂,常作为其他数据结构的基础。同时,文章还提供了C语言实现单链表的代码,以帮助加深对指针操作的理解。
最低0.47元/天 解锁文章
1742

被折叠的 条评论
为什么被折叠?



