算法导论10.2-5循环链表实现
循环链表插入,删除和查找的初步实现,但是感觉写的漏洞非常多,再研究研究
#include<iostream> using namespace std; struct my_list { my_list *pre,*next; int key; }; my_list* Init_list() { my_list *list = new my_list(); if(list == NULL) cout << "申请内存空间失败\n"; list->pre = list->next = list; return list; } my_list* Create_list() { my_list *list1 = new my_list(); int value = 0; my_list *list = list1; cout << "请输入各元素值:\n"; while(cin >> value) { my_list *temp = new my_list(); temp->key = value; list->next = temp; temp->pre = list; list = temp; } list->next = list1; list1->pre = list; return list1; } bool list_empty(my_list *list) { if(list->next == list && list->pre == list) return true; return false; } void list_insert(my_list *list, int i, int value) { my_list *temp = list->next; while(--i) { temp = temp->next; if(temp == list) { cerr << "插入位置错误\n"; exit(1); } } my_list *p = new my_list(); p->key = value; p->next = temp->next; temp->next->pre = p; temp->next = p; p->pre = temp; } void list_delete(my_list *list, int i) { my_list *temp = list->next; while(i--) { temp = temp->next; if(temp == NULL || temp == list) { cerr << "插入位置错误\n"; exit(1); } } my_list *temp1 = temp; temp1->pre->next = temp1->next; temp->next->pre = temp1->pre; free(temp1); } int list_search(my_list *list,int key) { my_list *temp = list->next; int i = 0; while(temp != list) { if(temp ->key == key) return i; temp = temp->next; ++i; } return -1; } void print(my_list *list) { my_list *temp = list->next; cout << "链表的元素是:\n"; while(temp != list) { cout << temp->key << " "; temp = temp->next; } cout << endl; } int main() { my_list *list = Init_list(); list = Create_list(); print(list); list_insert(list,2,10); print(list); list_delete(list,3); print(list); cout << list_search(list, 1) << endl; }