日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ class实现双向循环链表(完整代码)

發布時間:2023/12/4 c/c++ 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ class实现双向循环链表(完整代码) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

寫Delete_all的時候注意一下就好了,先判斷空白頭結點是不是為NULL

代碼如下:

#include <iostream> using namespace std; typedef int ElemType; #define NO 0class Node {friend class LinkList;public:Node(): next(NULL), prior(NULL) {};private:ElemType data;Node *next;Node *prior; };class LinkList {public:LinkList(): head(NULL) {};~LinkList() {Delete_all();}void Init();void TailCreateList(int n);Node *Locate_i(int i);Node *Locate_e(ElemType e);ElemType Get(int i);bool Insert(ElemType e, int i);bool Delete(int i);void Delete_all();void PrintList();private:Node *head; };void LinkList::Init() {Delete_all();head = NULL; }void LinkList::TailCreateList(int n) {Node *p, *s, *r;Delete_all();p = new Node();r = p;for (int i = 1; i <= n; i++) {s = new Node();cin >> s->data;r->next = s;s->prior = r;r = s;}r->next = p;p->prior = r;head = p; }Node *LinkList::Locate_i(int i) {if (i == 0)return head;Node *p;p = head->next;int j = 1;while ((p != head) && (j < i)) {j++;p = p->next;}if (i == j)return p;else {cout << "position is not correct!!!" << endl;return NULL;} }Node *LinkList::Locate_e(ElemType e) {Node *p;p = head->next;while ((p != head) && (p->data != e))p = p->next;if (p != head)return p;else {cout << e << " is not exist!!!" << endl;return NULL;} }bool LinkList::Insert(ElemType e, int i) {Node *p, *s;p = Locate_i(i - 1);if (p != NULL) {s = new Node();s->data = e;s->next = p->next;p->next->prior = s;p->next = s;s->prior = p;return true;} else {cout << "position is not correct!!!" << endl;return false;} }bool LinkList::Delete(int i) {Node *p;p = Locate_i(i);if (p != NULL) {p->prior->next = p->next;p->next->prior = p->prior;delete p;return true;} else {cout << "position is not correct!!!" << endl;return false;} }ElemType LinkList::Get(int i) {Node *p;p = head->next;int j = 1;while ((p != head) && (j < i)) {j++;p = p->next;}if (j == i)return p->data;else {cout << "position is not correct!!!" << endl;return NO;} }void LinkList::Delete_all() {Node *p, *q;p = head;if (p == NULL) {head = NULL;return;}q = p->prior;q->next = NULL;while (p != NULL) {q = p->next;delete p;p = q;}head = NULL; }void LinkList::PrintList() {Node *p;p = head->next;while (p != head) {cout << p->data << " ";p = p->next;}cout << endl; }int main() {LinkList l;l.Init();int n;cin >> n;l.TailCreateList(n);l.PrintList();l.Insert(30, 3);l.PrintList();l.Delete(4);l.PrintList();cout << l.Get(2) << endl;l.PrintList();return 0; }

測試結果:

總結

以上是生活随笔為你收集整理的C++ class实现双向循环链表(完整代码)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。