C++实现无头结点单链表

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值