小编这次要给大家分享的是C++如何实现单向链表,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。
为了练习一下对链表的理解,尝试手动造轮子,实现单向链表的右添加,左添加和删除的功能。
头文件
#pragma once #include<iostream> using namespace std; struct Node//节点 { int value; Node* next; Node(int a = 0, Node* n = NULL) :value(a), next(n) {} }; class List { private: Node* head = NULL;//头指针 Node* tail = NULL;//尾指针,便于在尾部添加节点 int size = 0; public: int getSize() { return size; }//获取链表大小 void print();//打印链表 void append(int a);//右添加 void appendleft(int a);//左添加 void remove(int a);//删除节点 };
源文件
#include "List.h"
void List::append(int a) { Node *p = new Node(a); if (head) { tail->next = p; tail = p; } else { head = p; tail = p; } size++; } void List::appendleft(int a) { Node *p = new Node(a); if (head) { p->next = head; head = p; } else { head = p; tail = p; } size++; } void List::remove(int a) { Node* p = head; bool flag = false; if (!head) { flag = false; cout << "链表已空,无需删除!" << endl; } else if (head->value == a && head != tail) { head = head->next; delete p; size--; flag = true; cout << "删除成功!" << endl; } else if (head->value == a && head == tail) { head = NULL, tail = NULL; delete p; size--; flag = true; cout << "删除成功!" << endl; } else { Node*q = head->next; while (q) { if (q->value == a && q != tail) { p->next = q->next; delete q; size--; flag = true; cout << "删除成功!" << endl; break; } else if (q->value == a && q == tail) { p->next = NULL; tail = p; delete q; size--; flag = true; cout << "删除成功!" << endl; break; } else { p = q; q = p->next; } } if (!flag) cout << "查无此值:" << a << endl; } } void List::print() { if (!head) cout << "链表为空,无法输出!" << endl; else { cout << "链表为:" ; Node*p = head; while (p) { cout << p->value << " "; p = p->next; } cout << endl; } }
主程序验证
int main() { List list1; list1.append(3); list1.append(4); list1.appendleft(5); list1.appendleft(6); list1.append(2); cout << "----链表大小:" << list1.getSize() << endl; list1.print(); list1.remove(5); cout << "----链表大小:" << list1.getSize() << endl; list1.print(); list1.remove(7); cout << "----链表大小:" << list1.getSize() << endl; list1.print(); list1.remove(6); cout << "----链表大小:" << list1.getSize() << endl; list1.print(); list1.remove(4); cout << "----链表大小:" << list1.getSize() << endl; list1.print(); list1.remove(3); cout << "----链表大小:" << list1.getSize() << endl; list1.print(); list1.remove(2); cout << "----链表大小:" << list1.getSize() << endl; list1.print(); system("pause"); return 0; }
验证结果
看完这篇关于C++如何实现单向链表的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。