概述
#include <iostream> using namespace std; typedef int ElemType; typedef struct DLnode{ DLnode*prior; DLnode*next; ElemType data; } DLinkList; //头插法 void CreateListF(DLinkList *&list, ElemType a[], int n) { DLinkList *s; int i; list = (DLinkList *)malloc(sizeof(DLinkList)); list->prior = list->next = NULL; for (i = 0; i < n; i++) { s = (DLinkList *)malloc(sizeof(DLinkList)); s->data = a[i]; s->next = list->next; if (list->next != NULL) list->next->prior = s; list->next = s; s->prior = list; } } //尾插法 void CreateListR(DLinkList *&list, ElemType a[], int n) { DLinkList *p, *s; list = (DLinkList *)malloc(sizeof(DLinkList)); list->prior = list->next = NULL; p = list; for (int i = 0; i < n; i++) { s = (DLinkList *)malloc(sizeof(DLinkList)); s->data = a[i]; s->next = p->next; s->prior = p; p->next = s; p = s; } } // 插入数据 bool ListInsert(DLinkList *&list, int i, ElemType e) { int j = 0; DLinkList *s, *p; p = list; while (j <i -1 && p != NULL) { j++; p = p->next; } if (p == NULL) { return false; } else { s = (DLinkList *)malloc(sizeof(DLinkList)); s->data = e; s->next = p->next; if (p->next != NULL) { p->next->prior = s; } p->next = s; s->prior = p; return true; } } //删除数据 bool Delnode(DLinkList *&list, int i, ElemType e) { int j = 0; DLinkList *p,*q; p = list; while (j < i - 1 && p != NULL) { j++; p = p->next; } if (p == NULL) { return false; } else { q = p->next; if (q == NULL) return false; e = q->data; p->next = q ->next; q->next->prior = p; free(q); return true; } } void DispList(DLinkList * list) { DLinkList *p; p = list->next; while (p != NULL) { cout << p->data << " "; p = p->next; } } int main() { const int n = 7; int a[n]; cout << "Input " << n << " numbers:"; for (int i = 0; i < n; i++) { cin >> a[i]; } DLinkList *lista, *listb; CreateListF(lista, a, n); CreateListR(listb, a, n); cout << "头(lista)"; DispList(lista); cout << endl << "尾(listb)"; DispList(listb); cout << endl << endl; int loca, m; cout << "输入要插入的数据和位置(lista):"; cin >> m >> loca; if (ListInsert(lista, loca, m)) { DispList(lista); cout << endl << endl; } else cout << "插入失败" << endl; cout << "输入要删除的数据的位置(lista):"; cin >> loca; if (Delnode(lista, loca, m)) { DispList(lista); cout << endl << endl; } else cout << "插入失败" << endl; }
参考书籍《数据结构教程》李春葆版
转载于:https://www.cnblogs.com/Arvin-JIN/p/8976820.html
最后
以上就是慈祥缘分为你收集整理的双链表基本操作的全部内容,希望文章能够帮你解决双链表基本操作所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复