您好,登錄后才能下訂單哦!
小編這次要給大家分享的是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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。