这是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