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 &