C++ single linked list 单链表的创建和执行(有头尾节点,考虑动态存储和内存泄漏等问题)(1)

这是C++ programming II这门课布置的一个小作业,核心是关于动态存储和指针的理解(尤其是new和delete的使用);花了不少时间,中途来csdn找资料也没有看到相关内容的经验分享,所以来写篇博文记录一下成果和心得。
代码旁有简单的注释,中英夹杂;不重要的我没有翻译,有问题的话欢迎评论留言。

首先声明一些习惯性用词:
head:头节点
tail:尾节点/尾部

创建(头文件)

LinkedList.h:

#ifndef INTLIST_H
#define INTLIST_H

#include <iostream>
using namespace std;

struct IntNode {
	int value;
	IntNode *next;
	IntNode(int value) : value(value), next(nullptr) {}
};

class IntList {
 private:
	IntNode *head;
	IntNode *tail;
 public:
	IntList();
	IntList(const IntList &cpy);
	~IntList();
	void push_front(int);
	void pop_front();
	bool empty() const;
	const int & front() const;
	const int & back() const;
	IntList& operator=(const IntList &rhs);
	void push_back(int);
	void clear();
	void selection_sort();
	void insert_ordered(int);
	void remove_duplicates();
	friend ostream & operator<<(ostream &, const IntList &rhs);
};

#endif

LinkedList.cpp里的构造函数:

IntList::IntList(): head(nullptr), tail(nullptr) {}

析构函数

最关键的来了,不注意的话从这一步开始就已经产生memory leak和dangling pointer了

IntList::~IntList(){
   if (head != nullptr){
     // 1. go to head 
     // 2. delete head and set it to null
     // 3. use the next of head to go to the next node in the IntList
     // 4. delete that node and set it to null
  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值