1.链表的默认构造, 拷贝构造,传参构造以及析构函数等。
- /********** BEGIN **********/
- #include
- #include
- #include "LinkedList.h"
-
- //默认构造函数,构造一个逻辑为空的链表
- LinkedList::LinkedList() {
- head = nullptr;
- size = 0;
- }
-
- //拷贝构造函数,构造一个逻辑上与参数内容相同的链表
- LinkedList::LinkedList(const LinkedList& rhs) {
- Node *p = rhs.head;
- head = nullptr;
- while (p != nullptr) {
- Node *node = new Node(p->data, nullptr);
- if (head == nullptr) {
- head = node;
- } else {
- Node *temp = head;
- while (temp->next != nullptr) {
- temp = temp->next;
- }
- temp->next = node;
- }
- p = p->next;
- }
- size = rhs.size;
- }
-
- //原生数组构造函数,构造一个内容与给定数组相同的链表
- LinkedList::LinkedList(int const a[], int n) {
- head = nullptr;
- size = 0;
- for (int i = 0; i < n; i++) {
- Node *node = new Node(a[i], nullptr);
- if (head == nullptr) {
- head = node;
- } else {
- Node *temp = head;
- while (temp->next != nullptr) {
- temp = temp->next;
- }
- temp->next = node;
- }
- size++;
- }
- }
-
- //填充构造函数,构造一个内容为n个value的链表
- LinkedList::LinkedList(int n, int value) {
- head = nullptr;
- size = 0;
- for (int i = 0; i < n; i++) {
- Node *node = new Node(value, nullptr);
- if (head == nullptr) {
- head = node;
- } else {
- Node *temp = head;
- while (temp->next != nullptr) {
- temp = temp->next;
- }
- temp->next = node;
- }
- size++;
- }
- }
-
- //析构函数,一定要自行实现,否则有内存泄漏
- LinkedList::~LinkedList() {
- Node *p = head;
- while (p != nullptr) {
- Node *temp = p;
- p = p->next;
- delete temp;
- }
- }