/* 实现双向链表。 */ #include<iostream> typedef int ElemType; typedef struct DuLnode { ElemType data; struct DuLnode* prior, * next; }DuLnode, *DuLinklist; bool InitList_L(DuLinklist& L) { /* 初始化双向列表。 */ L = new DuLnode; if (!L) return false; L->prior = NULL; L->next = NULL; return true; } bool CreateDuList_H(DuLinklist& L) { /* 头插法创建双向链表。 */ int n; DuLinklist s; std::cout << "请输入您要插入元素的个数" << std::endl; std::cin >> n; std::cout << "请以此输入您要插入的元素" << std::endl; std::cout << "头插法创建链表...." << std::endl; while (n--) { s = new DuLnode; if (!s) return false; std::cin >> s->data; s->next = L->next; s->prior = L; if(L->next) L->next->prior = s; L->next = s; } return true; } bool GetElem(DuLinklist L, int i, int& e) { /* 双向链表取值; */ DuLinklist p; p = L->next; for (int j = 0; j < i - 1; j++) { if (!p) return false; p = p->next; } e = p->data; return false; } int LocateElem(DuLinklist L, int e) { /* 在双向列表中查找元素。 */ DuLinklist p; p = L->next; int j = 1; while (p && p->data != e) { p = p->next; j++; } if (!p) return 0; return j; } bool Print_DuList(DuLinklist L) { DuLinklist p; p = L->next; if (!p) return false; while (p) { std::cout << p->data << " "; p = p->next; } std::cout << std::endl; return true; } bool ListInsert_L(DuLinklist& L, int i, int& e) { /* 在双向链表的第i个位置插入元素e; */ DuLinklist p, s; p = L->next; int j = 0; while (p && j++ < i) { p = p->next; } if (!p || j > i) return false; s = new DuLnode; s->data = e; p->prior->next = s; s->prior = p->prior; s->next = p; p->prior = s; return true; } bool ListDelete_L(DuLinklist& L, int i) { /* 双向链表之删除元素。 */ DuLinklist p; p = L->next; int j = 0; while (p && j < i-1) { p = p->next; j++; } if (!p || j > i) return false; if(p->next) p->next->prior = p->prior; p->prior->next = p->next; delete p; return true; } int main() { DuLinklist L; InitList_L(L); CreateDuList_H(L); Print_DuList(L); //int i, e; //std::cout << "请输入您要取得数的位置" << std::endl; //std::cin >> i; //GetElem(L, i, e); //std::cout << "您所取得数为:" << e << std::endl; //Print_DuList(L); //int e, i; //std::cout << "请您输入你要查找的元素" << std::endl; //std::cin >> e; //i = LocateElem(L, e); //std::cout << "您所查找的元素位于" << i << "位置" << std::endl; //int i, e; //std::cout << "请输入您要插入的元素的位置" << std::endl; //std::cin >> i; //std::cout << "请输入您要插入的元素" << std::endl; //std::cin >> e; //ListInsert_L(L, i, e); int i; std::cout << "请输入您要删除元素的位置" << std::endl; std::cin >> i; ListDelete_L(L, i); Print_DuList(L); return true; }