C++:单向链表实现

本文介绍了C++中实现无头结点单向链表的细节,包括深复制、内存管理、链表操作如插入、删除、排序等,并强调了在处理链表时需要注意的内存泄漏问题。通过实例解析了复制构造函数和重载赋值运算符的使用,以及如何避免内存泄漏。同时,提到了在调试时使用GDB解决运行时错误和内存泄漏问题的重要性。
摘要由CSDN通过智能技术生成

C++:单向链表实现

标签: C++

by 小威威


概况:
本次实验课的代码题难度较大(对于刚刚入门C++的人来说),对于解答者有一定的要求:1.了解链表的基本操作;2.对于浅复制与深复制有一定的了解并能加以区分;3.要有较强的gdb调试能力。(没有对程序进行调试一般情况下是得不到满分的,不排除你是超级大大神,第一次就写出了没有内存泄漏的代码)

这道题涉及到的知识点:
复制构造函数中的深复制,以及指针,动态内存分配,链表的建立,插入,删除,输出,排序,和删除链表,而且还要求通过gdb调试来解决runtime error 以及 内存泄漏等问题。

题目如下:
(15 C++ Lab) D&A Simple Linked List(Author: 叶嘉祺(TA))

Introduction

Knowledge points: (copy) constructor, deep copy, pointers, dynamic allocation, linked list algorithms, debug methods(GDB or IDE or output debug), memory leak.

In this Lab, you are going to implement a class named list which is a simple version for the list in stl. You are going to use dynamic memory allocation and pointer operations to finish this project.

I recommend you to:

Learn the knowledge points mentioned above.
Use local compilers to test you program rather than submit your answer to the system time after time.
Use local debug tools(GDB is recommended) to debug your code, especially for the memory leak problem. I can tell you that you will meet runtime error problem if you don’t use local debug tools.
Make use of your paper and pen to have some sketches because it’s a good way when you meet list.

Requirements:

Finish all the functions which have been declared inside the hpp file.

Details:

string toString(void) const

Return a visible list using ‘->’ to show the linked relation which is a string like:

1->2->3->4->5->NULL

void insert(int position, const int& data)

Add an element at the given position:

example0:

1->3->4->5->NULL

instert(1, 2);

1->2->3->4->5->NULL

example1:

NULL

insert(0, 1)

1->NULL

void list::erase(int position)

Erase the element at the given position

1->2->3->4->5->NULL

erase(0)

2->3->4->5->NULL

More

Happy coding…

题目已给出main.cpp与list.hpp

// main.cpp
#include <iostream>
#include <string>
#include "list.hpp"

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main() {
  list li;

  int n;
  cin >> n;

  for (int i = 0, data, pos; i < n; i++) {
    cin >> pos >> data;
    li.insert(pos, data);
  }

  cout &
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值