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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

一种基于平衡二叉树(AVL树)插入、查找和删除的简易图书管理系统

發布時間:2024/7/19 windows 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 一种基于平衡二叉树(AVL树)插入、查找和删除的简易图书管理系统 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

  • 1. 需求分析
  • 2. 項目核心設計
    • 2.1 結點插入
    • 2.2 結點刪除
  • 3 測試結果
  • 4 總結分析
    • 4.1 調試過程中的問題是如何解決的,以及對設計與實現的回顧討論和分析
    • 4.2 算法的時間和空間復雜度的分析,以及進一步改進的設想
    • 4.3 本次實驗的經驗和體會
  • 5 完整代碼(C++)

1. 需求分析

  • 設計和實現一個簡易的圖書管理系統,通過AVL樹的插入、查找和刪除等,完成各功能;
  • 每種書的登記內容至少包括書號、書名、著者、現存量和總庫存量等五項;
  • 書的數據用二叉排序樹存儲,借閱登記信息采用順序表—鏈表存儲;
  • 采編入庫:新購入一種書,經分類和確定書號之后登記到圖書帳目中去。如果這種書在帳中已有,則只將該書的總庫存量增加。圖書按登記的先后順序入庫(利用平衡二叉樹實現動態查找表的插入),書號為圖書的關鍵字。初始時,平衡二叉樹為空樹;
  • 借閱:如果一種書的現存量大于零,則借出一本,登記借閱者的圖書證號和歸還期限。借閱者借閱圖書時,先檢查借閱者有無超期未歸還圖書,如有,則不能借閱,如無,利用平衡二叉樹實現動態查找表的查找,登記借閱信息。同一種書不能重復借閱;
  • 歸還:注銷對借閱者的登記,改變該書的現存量(如果借閱者歸還所有的書,則注銷該借閱者的信息);
  • 清除庫存:將該圖書從平衡二叉樹中刪除,同時確保二叉樹平衡;
  • 凹入表打印平衡二叉樹,同時展示結點平衡因子bf,確保插入和刪除操作的正確性。
  • 2. 項目核心設計

    本程序使用C語言編寫與AVL樹相關的內容,故函數形參中未使用引用變量,需修改的實參均以指針形式呈現。后因圖書管理系統封裝函數的需求,更改.c文件為.cpp文件,從而引入class。

    項目核心部分為AVL樹的生成和結點刪除的同時如何保證樹的平衡性,下面對其實現原理進行解釋。基于此,構建圖書管理系統,系統邏輯和具體功能見MindMap。

    2.1 結點插入

    對結點插入的解釋以向其根結點左側插入為例,右插類似,不做贅述。
    若插入結點的關鍵詞小于根結點的關鍵詞,則插入根結點的左孩子。插入后,向根結點回溯時,返回一個taller,告知根結點因插入新結點而高度是否發生改變。此時分三種情況進行討論:

  • 若根結點原本右高(RH),則因新結點的插入而使根結點等高(EH),taller=FALSE告知根結點未因插入新結點而高度發生改變;
  • 若根結點原本等高(EH),則因新結點的插入而使根結點左高(LH),taller=TRUE告知根結點因插入新結點高度增高;
  • 若根結點原本左高(LH),向左插入新結點后,根結點失衡,故因左調平根結點。
  • else if(LT(elem.number,(*T)->data.number)) {//insert its left child treeif(!InsertAVLTree(&((*T)->lchild),taller,elem)) return ERROR;if(!*taller) return OK;switch((*T)->bf) { //update the BF of the nodecase LH://adjust to make it balancedL_Balance(T);*taller=FALSE; break;case EH: (*T)->bf=LH; *taller=TRUE; break;case RH: (*T)->bf=EH; *taller=FALSE; break;}//switch((*T)->bf)}

    左調平根結點時,根據根結點左孩子的平衡因子,判斷是LL型還是LR型,采用不同的調平方法。無論何種調平方法,都應遵循以下兩原則:

  • 確保二叉樹性質不變,即中序遍歷結果不變;
  • 使最小失衡子樹的高度降低。
  • 若左孩子的平衡因子為左高(LH),說明為LL型,修改根結點和其左孩子的平衡因子EH,向左旋轉根結點。若左孩子的平衡因子為右高(RH),說明為LR型,此時,根據其左孩子的右孩子的平衡因子,修改結點平衡因子再分三種情況進行討論:

  • 若其左的右孩子為左高(LH),則左和左的右孩子BF=EH,根結點BF=RH;
  • 若其左的右孩子為等高(EH),則左孩子和根結點BF=EH。(左的右孩子已為EH);
  • 若其左的右孩子為右高(RH),則根結點和左的右孩子BF=EH,左孩子BF=LH。
  • void LibManage::L_Balance(AVLTree *t){//adjust the root to make left tree balancedTNode *lc=(*t)->lchild,*rd;switch(lc->bf){ //check condition: LL or LR, through BF of root's lchildcase EH: //a case when deleting the node(*t)->bf=LH; lc->bf=RH;R_Rotate(t);break;case LH: //LL(*t)->bf=lc->bf=EH; //modify BFR_Rotate(t); //R rotate root nodebreak;case RH: //LRrd=lc->rchild;switch(rd->bf){ //modify BF according to different BF conditionscase LH: lc->bf=rd->bf=EH; (*t)->bf=RH; break;case EH: lc->bf=(*t)->bf=EH; break;case RH: rd->bf=(*t)->bf=EH; lc->bf=LH; break;}//switch(rd->bf)L_Rotate(&((*t)->lchild)); //part Left rotation, firstlyR_Rotate(t); //root Right rotation, thenbreak;}//switch(lc->bf) }

    修正平衡因子后,對失衡子樹進行旋轉。先對失衡子樹根結點的左孩子進行(局部)左旋轉,再對根結點進行(整體)右旋。至此,結點左插調平完成。以下為左調平操作示意圖解。

    2.2 結點刪除

    AVL樹結點的刪除操作同二叉搜索樹結點刪除相同,但刪除結點后需要調整使AVL樹重新平衡。根據所刪結點的雙親和孩子情況,分三種情況進行討論:

  • 若所刪結點為葉子結點(無孩子),直接刪除之。若其無雙親(即為AVL樹的根結點),置AVL樹根(root)為空(NULL);
  • 若所刪結點只有一孩子,令其雙親結點連接其孩子(至于是雙親的左還是右連接之,只需判斷雙親和孩子的關鍵詞大小,若雙親>孩子,則雙親左連之,反之,則雙親右連之)。若無雙親,可置樹根(root)為所刪結點的孩子;
  • 若所刪結點兩孩子均存在,則可通過尋找其(在中序遍歷下的)前驅或后繼,來實現刪除操作。為同程序一致,這里以尋找前驅為例。進入所刪結點的左孩子,向其右方(通過遍歷)尋至其最右方的結點(姑且稱作待刪結點的相鄰點),將待刪結點的值替換為相鄰點的值。再進入待刪結點的左子樹中(遞歸),刪除相鄰點。
  • else if(EQ(bknum,(*curT)->data.number)) {//find the node, and delete itif(!((*curT)->lchild)) {//if(the node has no left child or has neither left nor right one)if(!preT) *curT=(*curT)->rchild;//if(the node has no parent)else if(LT(bknum,preT->data.number)) preT->lchild=(*curT)->rchild;//check the current node is its parent's left child or its right oneelse preT->rchild=(*curT)->rchild;*shorter=TRUE;}//if(!((*curT)->lchild))else if(!((*curT)->rchild)) {//if(the node has no right child but has left one)if(!preT) *curT=(*curT)->lchild;//if(the node has no parent)else if(LT(bknum,preT->data.number)) preT->lchild=(*curT)->lchild;//check the current node is its parent's left child or its right oneelse preT->rchild=(*curT)->lchild;*shorter=TRUE;}//else if(!((*curT)->rchild))else {//if(the node has both right and left child)TNode *tempT=(*curT)->lchild; //enter curT's left childwhile(tempT->rchild) //find curNode's precursor in inorder traversetempT=tempT->rchild;BookCpy(&((*curT)->data),tempT->data); //assign the precursor's data to the node that needs to be deletedDeleteAVLTree(&((*curT)->lchild),NULL,shorter, tempT->data.number); //delete the precursor of the deleted elem in curT's left child

    接下來,對刪除結點后的調平工作進行解釋,同樣,以刪除根結點左子樹中的結點為例,右子樹中刪除操作類似,不做贅述。

    若所刪結點的關鍵詞<根結點的關鍵詞,則進入根結點左子樹中進行刪除操作。刪除后,向根結點回溯時,返回一個shorter,告知根結點因刪除結點而高度是否發生改變。此時分三種情況進行討論:

  • 根結點原本左高(LH),刪除后,根結點等高(EH),shorter=TRUE;
  • 根結點原本等高(EH),刪除后,根結點右高(RH),shorter=FALSE;
  • 根結點原本右高(RH),刪除后,根結點失衡,應當對其進行右調平R_Balance()操作。
  • 調平前,需根據根結點的右孩子的平衡因子,判斷調平后,失衡子樹shorter情況如何,此時分三種情況進行討論:

  • 根的右孩子BF=LH,調平后,shorter=TRUE;
  • 根的右孩子BF=EH,調平后,shorter=FALSE;
  • 根的右孩子BF=RH,調平后,shorter=TRUE。(也可與情況1歸并)
  • else if(LT(bknum,(*curT)->data.number)) {//if the keynum is less than the curT's numberif(!DeleteAVLTree(&((*curT)->lchild),*curT,shorter,bknum)) return ERROR;if(!*shorter) return OK;switch((*curT)->bf) {case LH: (*curT)->bf=EH; *shorter=TRUE; break;case EH: (*curT)->bf=RH; *shorter=FALSE; break;case RH://another 3 conditions need to be considered, according to curT's right child BFswitch((*curT)->rchild->bf) {case LH: *shorter=TRUE; break;case EH: *shorter=FALSE; break;case RH: *shorter=TRUE; break;}//switch((*curT)->rchild->bf)R_Balance(curT);}//switch((*curT)->bf)}//else if(LT(bknum,(*curT)->data.number))

    判斷回溯的shorter的結果后,開始右調平。右調平操作與結點插入時的右調平基本無異,但需在“通過根結點右孩子BF值判斷是RR型還是RL型失衡”時,增加一種EH的情況。因為在插入時,只考慮了因插入才會產生的LH和RH情況,未將刪除時所會遇到的EH納入其中。當BF=EH時,先更新各結點的平衡因子,根結點的BF=RH,根結點右孩子的BF=LH,再根結點左旋。(同理,左平衡操作時,也需補充“EH條件”)。

    void LibManage::R_Balance(AVLTree *t){//adjust the root to make right tree balancedTNode *rc=(*t)->rchild,*ld;switch(rc->bf){ //check condition: RL or RR, through BF of root's rchildcase EH: //a case when deleting the node(*t)->bf=RH; rc->bf=LH;L_Rotate(t);break;//......

    以下為右調平操作圖解。

    3 測試結果

    //為模擬方便起見,添加初始圖書、閱讀者和閱讀者的借閱數據
    //book={number,name,author,stock,total}
    Book book1={“01”,“PromisedLand”,“Obama”,6,8};
    Book book2={“02”,“Humans”,“Stanton”,4,5};
    Book book3={“03”,“Becoming”,“Michelle”,0,3};
    Book book4={“04”,“DeepEnd”,“Kinney”,0,6};
    InsertAVLTree(&tree,&taller,book1);
    InsertAVLTree(&tree,&taller,book2);
    InsertAVLTree(&tree,&taller,book3);
    InsertAVLTree(&tree,&taller,book4);
    //reader={code,name,telephone,firstarc}
    Reader reader1={1,“Sylvan”,“95566”,NULL};
    Reader reader2={2,“JIXIANG”,“10086”,NULL};
    AddReader(reader_list,reader1);
    AddReader(reader_list,reader2);
    //reader={booknumber,bookname,return date,*next}
    ArcBox arcbox1={“01”,“PromisedLand”,20251211,NULL};
    ArcBox arcbox2={“02”,“Humans”,20300201,NULL};
    AddReaderBook(reader_list.readers[0],arcbox1);
    AddReaderBook(reader_list.readers[0],arcbox2);
    AddReaderBook(reader_list.readers[1],arcbox1);

    (以下內容均來自終端)
    //啟動圖書管理系統,設置系統時間
    Launch Library Management System Successfully!
    Set current time:20201120 successfully!

    //菜單界面,待用戶輸入指令 * * * MENU * * * (1). Add books (2). Lend books (3). Return books (4). Erase books (5). Print All Books (6). Print All Readers (7). *(Testing MODE) (0). [ E X I T ] * * * * * * * * * Menu->Option: //功能一、采編入庫 Menu->Option: 1 - - - - Add Book - - - - Book Number: ISBN 01 Increment: 2 Find the BOOK... Would you like to increase it? (y/n)... y Original stock: 6 Original total amount: 8 - - - - Book Info - - - - Name: PromisedLand Author: Obama Number: ISBN 01 Total: 10 Stock: 8 - - - - - - - - - - - - - Increase successfully! Menu->Option: 1 - - - - Add Book - - - - Book Number: ISBN 05 Increment: 3 ERROR: Can't find BOOK: ISBN 05 Would you like to create a new item? (y/n)... y Number: ISBN 05 Stock/Total: 3 Name: Sherlock Author: Arthur - - - - Book Info - - - - Name: Sherlock Author: Arthur Number: ISBN 05 Total: 3 Stock: 3 - - - - - - - - - - - - - Add new book successfully! //功能二、借閱 Menu->Option: 2 - - - - Lend Book - - - - Reader Code: 01 - - - - Reader Info - - - - Name: Sylvan Code: 00001 Tele: 95566 Borrowed books: <Humans> | ISBN 02 | Deadline:20300201([Normal]) <PromisedLand> | ISBN 01 | Deadline:20251211([Normal]) - - - - - - - - - - - - - Book Number to lend: ISBN 02 No borrow permission: The reader has borrowed a same book <Humans>. //……相同操作省略 Book Number to lend: ISBN 03 ERROR: Book Stock of <Becoming> is not enough... Menu->Option: 2 - - - - Lend Book - - - - Reader Code: 02 - - - - Reader Info - - - - Name: JIXIANG Code: 00002 Tele: 10086 Borrowed books: <PromisedLand> | ISBN 01 | Deadline:20251211([Normal]) - - - - - - - - - - - - - Book Number to lend: ISBN 02 Return Date(e.g.20201230): 20191230 Lend Book Successfully! Menu->Option: 2 - - - - Lend Book - - - - Reader Code: 02 - - - - Reader Info - - - - Name: JIXIANG Code: 00002 Tele: 10086 Borrowed books: <Humans> | ISBN 02 | Deadline:20191230(![Overdue]!) <PromisedLand> | ISBN 01 | Deadline:20251211([Normal]) - - - - - - - - - - - - - No borrow permission: The reader has a book <Humans> needs to be returned before 20191230 Menu->Option: 2 - - - - Lend Book - - - - Reader Code: 05 ERROR: Can't find reader 00005... Would you like to create one? (y/n)... y Code: 00005 Name: Benedict Tele: 197362 - - - - Reader Info - - - - Name: Benedict Code: 00005 Tele: 197362 Borrowed books: (Empty) - - - - - - - - - - - - - Add reader successfully! Book Number to lend: ISBN 01 Return Date(e.g.20201230): 20201231 Lend Book Successfully! //功能三、還書 Menu->Option: 3 - - - - Return Book - - - - Reader Code: 01 - - - - Reader Info - - - - Name: Sylvan Code: 00001 Tele: 95566 Borrowed books: <Humans> | ISBN 02 | Deadline:20300201([Normal]) <PromisedLand> | ISBN 01 | Deadline:20251211([Normal]) - - - - - - - - - - - - - Book Number to return: ISBN 02 Return Successfully! Menu->Option: 3 - - - - Return Book - - - - Reader Code: 01 - - - - Reader Info - - - - Name: Sylvan Code: 00001 Tele: 95566 Borrowed books: <PromisedLand> | ISBN 01 | Deadline:20251211([Normal]) - - - - - - - - - - - - - Book Number to return: ISBN 01 Warning: Reader Sylvan has returned all books, now erase his or her info from the memory... Erased successfully! Return Successfully! Menu->Option: 6 - - - - Reader Info - - - - Name: JIXIANG Code: 00002 Tele: 10086 Borrowed books: <PromisedLand> | ISBN 01 | Deadline:20251211([Normal]) - - - - - - - - - - - - - //功能四、清除庫存 Menu->Option: 4 - - - - Erase Book - - - - Book Number to erase: ISBN 01 Delete book successfully! Menu->Option: 5 - - - - Book Info - - - - Name: Becoming Author: Michelle Number: ISBN 03 Total: 3 Stock: 0 - - - - Book Info - - - - Name: Humans Author: Stanton Number: ISBN 02 Total: 5 Stock: 4 - - - - Book Info - - - - Name: DeepEnd Author: Kinney Number: ISBN 04 Total: 6 Stock: 0 - - - - - - - - - - - - - //功能五、展示所有圖書 //功能六、展示所有借閱者 //功能七、測試模式:便捷地測試AVL樹的插入與刪除。

    4 總結分析

    4.1 調試過程中的問題是如何解決的,以及對設計與實現的回顧討論和分析

    平衡二叉排序樹(Balanced Binary Sort Tree),又稱AVL樹,是一種時間復雜度較低的理想的動態查找表。通過在樹結點TNode中,增設整型變量bf(即平衡因子balance factor),來判定結點是否平衡。Bf為該結點左子樹高與右子樹高的差值,當其絕對值超過1以后,結點失衡,需要對其進行調平操作。

    寫程序過程中,遇到邏輯問題后,通過一步步debug,發現問題,解決問題。

    4.2 算法的時間和空間復雜度的分析,以及進一步改進的設想

    經分析,平衡二叉樹的查找、插入和刪除其時間復雜度均為1

    ?(log?n).\bigcirc \left ( \log n\right ). ?(logn).

    是一種理想的動態查找表。

    4.3 本次實驗的經驗和體會

    通過使用C語言編寫平衡二叉樹插入和刪除部分,大量使用指針變量,深入理解了指針的含義和用法。函數中,重復使用回溯的方法進行二叉樹平衡,加強了對算法邏輯對掌握。

    使用C++編寫圖書管理部分,學習和培養了考慮項目要全面的能力。

    語法錯誤越來越少,而真正困難的邏輯部分問題增多。

    在編寫平衡二叉樹插入和刪除時,調試過程中遇到許多問題,如旋轉錯誤、結點平衡因子錯誤等等。Edsger W. Dijkstra曾說過,

    “有效的程序員不應該浪費很多時間用于程序調試,他們應該一開始就不要把故障引入。” 2

    表明,在寫程序前就應當理清邏輯和考慮所有情況,因此,后續還需繼續培養編程的邏輯性和嚴謹性。

    5 完整代碼(C++)

    #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h>/* status macro definition */ #define OK 1 #define ERROR 0 #define OVER_FLOW -2/* memory length macro definition */ #define MAXNAMELEN 15 #define MAXBOOKNUMBERLEN 20 #define MAXREADERNUM 20 //the max amount of all readers #define MAXREADERCODEDIGIT 5 //max reader code digits #define INDENTATION 0 //for printing the BiTree/* some macros related to AVLTree */ #define EQ(a,b) (!strcmp((a),(b))) #define LT(a,b) (strcmp((a),(b))<0) #define LH +1 #define EH 0 #define RH -1typedef int Status; typedef enum {FALSE,TRUE} boolean; typedef char *KeyType; typedef char NameType[MAXNAMELEN]; typedef char *BookNum,BookNumType[MAXBOOKNUMBERLEN]; typedef char TeleType[11+1]; //telephone: 11digits typedef unsigned int DateType; //return date //typedef Book DataType; //data type in TNodetypedef struct{BookNumType number; //no prefix 'ISBN'NameType name;NameType author;int stock; //current amount of the bookint total; //total amount of the book }Book,DataType;typedef struct TNode{DataType data;int bf; //balance factorstruct TNode *lchild,*rchild; }TNode,*AVLTree;typedef struct ArcBox{BookNumType bknum;NameType bknam;DateType return_date; //e.g. 20010205struct ArcBox *next; }ArcBox;typedef struct{int code;NameType name;TeleType tele; //telephoneArcBox *first_arc; }Reader;typedef struct{Reader *readers;int length,size; }AdjList;class LibManage{ public:AVLTree tree;AdjList reader_list;DateType current_date;LibManage();~LibManage() {DestoryTree(tree);}void Menu();void AddBook();void LendBook();void ReturnBook();void EraseBook();void OutputBooks();void OutputReaders();void TestMode(); private:void gettime();void PrintBook(Book b);void PrintBiTree_Simple(AVLTree T,int indent);void PrintBiTree_Detail(AVLTree T);void BookCpy(Book *a,Book b);void L_Rotate(AVLTree *t);void R_Rotate(AVLTree *t);void L_Balance(AVLTree *t);void R_Balance(AVLTree *t);TNode* SearchAVLTree(AVLTree T,BookNum bn);Status InsertAVLTree(AVLTree *T,boolean *taller,DataType elem);Status DeleteAVLTree(AVLTree *curT,AVLTree preT,boolean *shorter,KeyType bknum);Status InitAdjList(AdjList &list);Status AddReader(AdjList &list,const Reader &r);Status AddReaderBook(Reader &r,const ArcBox &ab);Status SearchReader(AdjList list,int code);Status DeleteReader(AdjList &list,int code);Status CheckBorrowPermission(Reader r,BookNum bknum=NULL);ArcBox* SearchBorrowedBook(Reader r,KeyType bknum,ArcBox* &prep);void ReaderCpy(Reader &r1,const Reader &r2);void PrintReader(const Reader &r);void PrintBorrowedBooks(Reader r);void DestoryTree(AVLTree &T); };void LibManage::gettime(){//get system time and convert it to unsigned inttime_t rawtime;struct tm *ptminfo;time(&rawtime); //get time raw infoptminfo=localtime(&rawtime); //convert raw time info to processed and readable time infocurrent_date=((ptminfo->tm_year)+1900)*10000+(ptminfo->tm_mon)*100+(ptminfo->tm_mday);printf("Set current time:%u successfully! \n",current_date); }LibManage::LibManage() {tree=NULL; //initialize treeInitAdjList(reader_list); //initialize AdjListprintf("Launch Library Management System Successfully! \n");gettime();/* Simulate a library, so add some items first *///book={number,name,author,stock,total}boolean taller=FALSE;Book book1={"01","PromisedLand","Obama",6,8};Book book2={"02","Humans","Stanton",4,5};Book book3={"03","Becoming","Michelle",0,3};Book book4={"04","DeepEnd","Kinney",0,6};InsertAVLTree(&tree,&taller,book1);InsertAVLTree(&tree,&taller,book2);InsertAVLTree(&tree,&taller,book3);InsertAVLTree(&tree,&taller,book4);//reader={code,name,telephone,firstarc}Reader reader1={1,"Sylvan","95566",NULL};Reader reader2={2,"JIXIANG","10086",NULL};AddReader(reader_list,reader1);AddReader(reader_list,reader2);//reader={booknumber,bookname,return date,*next}ArcBox arcbox1={"01","PromisedLand",20251211,NULL};ArcBox arcbox2={"02","Humans",20300201,NULL};AddReaderBook(reader_list.readers[0],arcbox1);AddReaderBook(reader_list.readers[0],arcbox2);AddReaderBook(reader_list.readers[1],arcbox1); }void LibManage::DestoryTree(AVLTree &T){//free the memory of the tree, using post-order traverse to guarantee that the node's parent won't get lostif(!T) return;DestoryTree(T->lchild);DestoryTree(T->rchild);free(T); T=NULL; }//the following function is related to AVLTreevoid LibManage::L_Rotate(AVLTree *t){//left rotate root node, and update the rootTNode *rc=(*t)->rchild;(*t)->rchild=rc->lchild;rc->lchild=*t;(*t)=rc; } void LibManage::R_Rotate(AVLTree *t){//right rotate root node, and update the rootTNode *lc=(*t)->lchild;(*t)->lchild=lc->rchild;lc->rchild=*t;(*t)=lc; } void LibManage::L_Balance(AVLTree *t){//adjust the root to make left tree balancedTNode *lc=(*t)->lchild,*rd;switch(lc->bf){ //check condition: LL or LR, through BF of root's lchildcase EH: //a case when deleting the node(*t)->bf=LH; lc->bf=RH;R_Rotate(t);break;case LH: //LL(*t)->bf=lc->bf=EH; //modify BFR_Rotate(t); //R rotate root nodebreak;case RH: //LRrd=lc->rchild;switch(rd->bf){ //modify BF according to different BF conditionscase LH: lc->bf=rd->bf=EH; (*t)->bf=RH; break;case EH: lc->bf=(*t)->bf=EH; break;case RH: rd->bf=(*t)->bf=EH; lc->bf=LH; break;}//switch(rd->bf)L_Rotate(&((*t)->lchild)); //part Left rotation, firstlyR_Rotate(t); //root Right rotation, thenbreak;}//switch(lc->bf) } void LibManage::R_Balance(AVLTree *t){//adjust the root to make right tree balancedTNode *rc=(*t)->rchild,*ld;switch(rc->bf){ //check condition: RL or RR, through BF of root's rchildcase EH: //a case when deleting the node(*t)->bf=RH; rc->bf=LH;L_Rotate(t);break;case RH: //RR(*t)->bf=rc->bf=EH; //modify BFL_Rotate(t); //L rotate root nodebreak;case LH: //RLld=rc->lchild;switch(ld->bf){ //modify BF according to different BF conditionscase LH: (*t)->bf=rc->bf=EH; ld->bf=RH; break;case EH: rc->bf=(*t)->bf=EH; break;case RH: ld->bf=rc->bf=EH; (*t)->bf=LH; break;}//switch(rd->bf)R_Rotate(&((*t)->rchild)); //part Right rotation, firstlyL_Rotate(t); //root Left rotation, thenbreak;}//switch(lc->bf) }TNode* LibManage::SearchAVLTree(AVLTree T,BookNum bn){/* if the booknum can be found in AVLTree, then return its address, else return NULL */if(!T) return NULL;if(EQ(bn,T->data.number)) return T;if(LT(bn,T->data.number)) return SearchAVLTree(T->lchild,bn);return SearchAVLTree(T->rchild,bn); }Status LibManage::InsertAVLTree(AVLTree *T,boolean *taller,DataType elem){/* insert an elem to AVLTree, and adjust the tree to keep its balance. If elem has existed, then return ERROR, else return OK *//* parameter 'taller' means that after inserting the elem, the tree is taller or not. */if(!*T) { //create a new node*T=(TNode*)malloc(sizeof(TNode));if(!*T) exit(OVER_FLOW);BookCpy(&((*T)->data),elem);(*T)->bf=EH;(*T)->lchild=(*T)->rchild=NULL;*taller=TRUE;}else if(EQ(elem.number,(*T)->data.number)) {//if the node has already existedPrintBook((*T)->data);printf("ERROR: book <%s> has already been in the AVL Tree. \n",elem.name);*taller=FALSE;return ERROR;}else if(LT(elem.number,(*T)->data.number)) {//insert its left child treeif(!InsertAVLTree(&((*T)->lchild),taller,elem)) return ERROR;if(!*taller) return OK;switch((*T)->bf) { //update the BF of the nodecase LH://adjust to make it balancedL_Balance(T);*taller=FALSE; break;case EH: (*T)->bf=LH; *taller=TRUE; break;case RH: (*T)->bf=EH; *taller=FALSE; break;}//switch((*T)->bf)}else {//insert its right child treeif(!InsertAVLTree(&((*T)->rchild),taller,elem)) return ERROR;if(!*taller) return OK;switch((*T)->bf) { //update the BF of the nodecase LH: (*T)->bf=EH; *taller=FALSE; break;case EH: (*T)->bf=RH; *taller=TRUE; break;case RH://adjust to make it balancedR_Balance(T);*taller=FALSE; break;}//switch((*T)->bf)}return OK; }Status LibManage::DeleteAVLTree(AVLTree *curT,AVLTree preT,boolean *shorter,KeyType bknum){/* delete a node in AVLTree according to its book number, and adjust the tree to keep its balance. If elem has existed, then return OK, else return ERROR *///?SylvanDing/* parameter 'shorter' means that after deleting the node, the tree is shorter or not. */if(!*curT) {//if the node doesn't existprintf("ERROR: Can't find BOOK: ISBN %s \n",bknum);*shorter=FALSE;return ERROR;}//if(!*curT)else if(EQ(bknum,(*curT)->data.number)) {//find the node, and delete itif(!((*curT)->lchild)) {//if(the node has no left child or has neither left nor right one)if(!preT) *curT=(*curT)->rchild;//if(the node has no parent)else if(LT(bknum,preT->data.number)) preT->lchild=(*curT)->rchild;//check the current node is its parent's left child or its right oneelse preT->rchild=(*curT)->rchild;*shorter=TRUE;}//if(!((*curT)->lchild))else if(!((*curT)->rchild)) {//if(the node has no right child but has left one)if(!preT) *curT=(*curT)->lchild;//if(the node has no parent)else if(LT(bknum,preT->data.number)) preT->lchild=(*curT)->lchild;//check the current node is its parent's left child or its right oneelse preT->rchild=(*curT)->lchild;*shorter=TRUE;}//else if(!((*curT)->rchild))else {//if(the node has both right and left child)TNode *tempT=(*curT)->lchild; //enter curT's left childwhile(tempT->rchild) //find curNode's precursor in inorder traversetempT=tempT->rchild;BookCpy(&((*curT)->data),tempT->data); //assign the precursor's data to the node that needs to be deletedDeleteAVLTree(&((*curT)->lchild),NULL,shorter, tempT->data.number); //delete the precursor of the deleted elem in curT's left childif(!*shorter) return OK;switch((*curT)->bf) {case LH: (*curT)->bf=EH; *shorter=TRUE; break;case EH: (*curT)->bf=RH; *shorter=FALSE; break;case RH://another 3 conditions need to be considered, according to curT's right child BFswitch((*curT)->rchild->bf) {case LH: *shorter=TRUE; break;case EH: *shorter=FALSE; break;case RH: *shorter=TRUE; break;}//switch((*curT)->rchild->bf)R_Balance(curT);}//switch((*curT)->bf)}}//else if(EQ(bknum,(*curT)->data.number))else if(LT(bknum,(*curT)->data.number)) {//if the keynum is less than the curT's numberif(!DeleteAVLTree(&((*curT)->lchild),*curT,shorter,bknum)) return ERROR;if(!*shorter) return OK;switch((*curT)->bf) {case LH: (*curT)->bf=EH; *shorter=TRUE; break;case EH: (*curT)->bf=RH; *shorter=FALSE; break;case RH://another 3 conditions need to be considered, according to curT's right child BFswitch((*curT)->rchild->bf) {case LH: *shorter=TRUE; break;case EH: *shorter=FALSE; break;case RH: *shorter=TRUE; break;}//switch((*curT)->rchild->bf)R_Balance(curT);}//switch((*curT)->bf)}//else if(LT(bknum,(*curT)->data.number))else {//if the keynum is larger than the curT's number, enter its right childif(!DeleteAVLTree(&((*curT)->rchild),*curT,shorter,bknum)) return ERROR;if(!*shorter) return OK;switch((*curT)->bf) {case LH://another 3 conditions need to be considered, according to curT's left child BFswitch((*curT)->lchild->bf) {case LH: *shorter=TRUE; break;case EH: *shorter=FALSE; break;case RH: *shorter=TRUE; break;}//switch((*curT)->rchild->bf)L_Balance(curT);case EH: (*curT)->bf=LH; *shorter=FALSE; break;case RH: (*curT)->bf=EH; *shorter=TRUE; break;}//switch((*curT)->bf)}//elsereturn OK; }void LibManage::TestMode(){//this mode is for testing AVLTree's insertion and deletion quickly and easilyBook bk={"","","",0,0};AVLTree testT=NULL; boolean flag;printf("- - - Testing Mode - - -\n");printf("//This mode allows you to test AVLTree's insertion and deletion quickly and easily. Whenever you insert or delete an item, it will print the AVLTree: KeyValue(BalanceFactor) \n//Have created a new Empty AVLTree for testing... \n//Input numbers(like 01,21,36...) to insert it, input 'end' to stop inserting. \n");//?SylvanDingdo{flag=FALSE;scanf("%s",bk.number);getchar();if(EQ(bk.number,"end")) break;InsertAVLTree(&testT,&flag,bk);printf("* Tree Print * \n");PrintBiTree_Simple(testT,INDENTATION);}while(1);printf("//End inserting, and then you can input the item you wanna delete, input 'quit' to exit testing mode... \n");do{flag=FALSE;scanf("%s",bk.number);getchar();if(EQ(bk.number,"quit")) break;DeleteAVLTree(&testT,NULL,&flag,bk.number);printf("* Tree Print * \n");PrintBiTree_Simple(testT,INDENTATION);}while(1);printf("//Exit TESTING MODE... \n"); }//the following function is about Library Managementvoid LibManage::Menu(){printf("* * * MENU * * *\n");printf("(1). Add books\n");printf("(2). Lend books\n");printf("(3). Return books\n");printf("(4). Erase books\n");printf("(5). Print All Books\n");printf("(6). Print All Readers\n");printf("(7). *(Testing MODE)\n");printf("(0). [ E X I T ]\n");printf("* * * * * * * * *\n"); }void LibManage::BookCpy(Book *a,Book b){//copy b's info and assign it to astrcpy(a->number,b.number);strcpy(a->name,b.name);strcpy(a->author,b.author);a->stock=b.stock;a->total=b.total; }void LibManage::PrintBook(Book b){printf("- - - - Book Info - - - -\n");printf("Name: %s\n",b.name);printf("Author: %s\n",b.author);printf("Number: ISBN %s\n",b.number);printf("Total: %d\n",b.total);printf("Stock: %d\n",b.stock);printf("- - - - - - - - - - - - -\n"); }void LibManage::PrintBiTree_Simple(AVLTree T,int indent){if(!T) return;printf("%*s%s(%d)\n",indent,"",T->data.number,T->bf);PrintBiTree_Simple(T->lchild,indent+1);PrintBiTree_Simple(T->rchild,indent+1); }void LibManage::PrintBiTree_Detail(AVLTree T){if(!T) return;PrintBook(T->data);PrintBiTree_Detail(T->lchild);PrintBiTree_Detail(T->rchild); }void LibManage::AddBook(){//to add a new book when bknum-related book doesn't exist in AVLTree, or increase its original amountAVLTree *T=&tree;TNode *node=NULL; char flag;BookNumType bknum; int amount;printf("- - - - Add Book - - - -\n");printf("Book Number: ISBN ");scanf("%s",bknum);printf("Increment: ");scanf("%d",&amount);getchar();if(!(node=SearchAVLTree(*T,bknum))) {boolean taller=FALSE;Book new_book; NameType bk_name,aut_name;printf("ERROR: Can't find BOOK: ISBN %s \n Would you like to create a new item? (y/n)...\n",bknum);scanf("%c",&flag);switch(flag){case 'n':case 'N': return; break;case 'y':case 'Y':printf("Number: ISBN %s\n",bknum);printf("Stock/Total: %d\n",amount);printf("Name: ");scanf("%s",bk_name);printf("Author: ");scanf("%s",aut_name);strcpy(new_book.number,bknum);strcpy(new_book.name,bk_name);strcpy(new_book.author,aut_name);new_book.stock=new_book.total=amount;if(!InsertAVLTree(T,&taller,new_book)) return;PrintBook(new_book);printf("Add new book successfully! \n");break;default: printf("Error: Wrong command, try again...\n");}//switch(flag)}//if(!(node=SearchAVLTree(*T,bknum)))else {printf("Find the BOOK...\nWould you like to increase it? (y/n)...\n");scanf("%c",&flag);switch(flag){case 'n':case 'N': return; break;case 'y':case 'Y':printf("Original stock: %d \nOriginal total amount: %d \n",node->data.stock,node->data.total);node->data.stock+=amount;node->data.total+=amount;PrintBook(node->data);printf("Increase successfully! \n");break;default: printf("Error: Wrong command, try again...\n");}//switch(flag)}//else }void LibManage:: LendBook(){//to lend booksint code,index; char flag;printf("- - - - Lend Book - - - -\n");printf("Reader Code: ");scanf("%d",&code);getchar();if((index=SearchReader(reader_list,code))<0) {index=reader_list.length;Reader newreader; newreader.first_arc=NULL;printf("ERROR: Can't find reader %0*d...\nWould you like to create one? (y/n)...\n",MAXREADERCODEDIGIT,code);scanf("%c",&flag);switch(flag){case 'n':case 'N': return; break;case 'y':case 'Y':printf("Code: %0*d \n",MAXREADERCODEDIGIT,code);newreader.code=code;printf("Name: ");scanf("%s",newreader.name);printf("Tele: ");scanf("%s",newreader.tele);if(!AddReader(reader_list,newreader)) return;PrintReader(reader_list.readers[reader_list.length-1]);printf("Add reader successfully! \n");break;default: printf("Error: Wrong command, try again...\n"); return;}//switch(flag)}//if(index<0)else {PrintReader(reader_list.readers[index]);if(!CheckBorrowPermission(reader_list.readers[index])) return;}//if(index>=0)BookNumType bknum; TNode *tptr;printf("Book Number to lend: ISBN ");scanf("%s",bknum);if(!CheckBorrowPermission(reader_list.readers[index],bknum)) return;if(!(tptr=SearchAVLTree(tree,bknum)))printf("ERROR: Can't find book: %s in Library System... \n",bknum);else if(tptr->data.stock<=0)printf("ERROR: Book Stock of <%s> is not enough... \n",tptr->data.name);else {ArcBox *new_arcbox=(ArcBox*)malloc(sizeof(ArcBox));if(!new_arcbox) exit(OVER_FLOW);--tptr->data.stock;printf("Return Date(e.g.20201230): ");scanf("%u",&(new_arcbox->return_date));strcpy(new_arcbox->bknum,bknum);strcpy(new_arcbox->bknam,tptr->data.name);new_arcbox->next=reader_list.readers[index].first_arc;reader_list.readers[index].first_arc=new_arcbox;printf("Lend Book Successfully! \n");} }void LibManage::ReturnBook(){//to return booksint code,index; TNode *tptr;BookNumType bknum; ArcBox *abptr,*pre_abptr;printf("- - - - Return Book - - - -\n");printf("Reader Code: ");scanf("%d",&code);getchar();if((index=SearchReader(reader_list,code))<0) {printf("ERROR: Can't find reader %0*d...\n",MAXREADERCODEDIGIT,code);return;}PrintReader(reader_list.readers[index]);printf("Book Number to return: ISBN ");scanf("%s",bknum);if(!(abptr=SearchBorrowedBook(reader_list.readers[index],bknum,pre_abptr))) {printf("ERROR: No lended book: %s...\n",bknum);return;}if(!pre_abptr)reader_list.readers[index].first_arc=abptr->next;elsepre_abptr->next=abptr->next;free(abptr);if(!reader_list.readers[index].first_arc) {printf("Warning: Reader %s has returned all books, now erase his or her info from the memory... \n",reader_list.readers[index].name);DeleteReader(reader_list,index);printf("Erased successfully! \n");}if((tptr=SearchAVLTree(tree,bknum)))++tptr->data.stock;printf("Return Successfully! \n"); }void LibManage::EraseBook(){//to erase bookBookNumType bknum; boolean shorter;printf("- - - - Erase Book - - - -\n");printf("Book Number to erase: ISBN ");scanf("%s",bknum);getchar();if(DeleteAVLTree(&tree,NULL,&shorter,bknum))printf("Delete book successfully! \n"); }void LibManage::OutputBooks(){//in-order traverse the AVLTreeif(!tree){printf("No book... \n");return;}PrintBiTree_Detail(tree); }void LibManage::OutputReaders(){if(reader_list.length<=0) {printf("No reader... \n");return;}for(int i=0;i<reader_list.length;++i)PrintReader(reader_list.readers[i]); }//the following function is about Readers ManagementStatus LibManage::InitAdjList(AdjList &list){//initialize reader adjacency listif(!(list.readers=(Reader*)malloc(MAXREADERNUM*sizeof(Reader)))) exit(OVER_FLOW);list.length=0; list.size=MAXREADERNUM;return OK; }Status LibManage::AddReader(AdjList &list, const Reader &newr){//add a new reader to reader listif(list.length>=list.size) {printf("ERROR: System unable to hold more readers... \n");return ERROR;}ReaderCpy(list.readers[list.length++],newr);return OK; }Status LibManage::AddReaderBook(Reader &r,const ArcBox &ab){//for stimulating a whole library management//no real functionArcBox *abptr=(ArcBox*)malloc(sizeof(ArcBox));if(!abptr) exit(OVER_FLOW);strcpy(abptr->bknum,ab.bknum);strcpy(abptr->bknam,ab.bknam);abptr->return_date=ab.return_date;abptr->next=r.first_arc;r.first_arc=abptr;return OK; }Status LibManage::SearchReader(AdjList list,int code){//if 'code' exists, then return its index, else return -1int index=0;while(index<list.length&&code!=list.readers[index].code) ++index;if(index<list.length) return index;else return -1; }Status LibManage::DeleteReader(AdjList &list,int index){while(index<list.length) {ReaderCpy(list.readers[index],list.readers[index+1]);++index;}--list.length;return OK; }Status LibManage::CheckBorrowPermission(Reader r,BookNum bknum){//if the second parameter 'bknum'=NULL, only check whether the borrower has overdue unreturned book, if he does, return 0, else return 1//if the 'bknum'!=NULL, then check if there has any same book that he has already borrowed. if he does, return 0, else return 1ArcBox *p=r.first_arc;if(!bknum) {while(p&&p->return_date>=current_date)p=p->next;if(p) {printf("No borrow permission: The reader has a book <%s> needs to be returned before %u \n",p->bknam,p->return_date);return 0;}else return 1;}//if(!bknum)else {while(p&&!EQ(bknum,p->bknum))p=p->next;if(p) {printf("No borrow permission: The reader has borrowed a same book <%s>. \n",p->bknam);return 0;}else return 1;}//else }ArcBox* LibManage::SearchBorrowedBook(Reader r,KeyType bknum,ArcBox* &prep){//if bknum can be found in reader's borrowed list, then return its arcbox's address, else return NULL.//prep return temp's precursor, when it has no precursor, return NULLArcBox *temp=r.first_arc; prep=NULL;while(temp&&!EQ(bknum,temp->bknum)){prep=temp;temp=temp->next;}return temp; }void LibManage::ReaderCpy(Reader &r1,const Reader &r2){//copy reader's info from r2 to r1strcpy(r1.name,r2.name);strcpy(r1.tele,r2.tele);r1.code=r2.code;r1.first_arc=r2.first_arc; }void LibManage::PrintReader(const Reader &r){printf("- - - - Reader Info - - - -\n");printf("Name: %s\n",r.name);printf("Code: %0*d\n",MAXREADERCODEDIGIT,r.code);printf("Tele: %s\n",r.tele);PrintBorrowedBooks(r);printf("- - - - - - - - - - - - -\n"); }void LibManage::PrintBorrowedBooks(Reader r){printf("Borrowed books: \n");if(!r.first_arc) printf("\t(Empty) \n");while(r.first_arc) {printf("<%s> | ISBN %s | Deadline:%u(%s)\n",r.first_arc->bknam,r.first_arc->bknum,r.first_arc->return_date,current_date>r.first_arc->return_date? "![Overdue]!":"[Normal]");r.first_arc=r.first_arc->next;} }int main(int argc, char *argv[]){LibManage LMSystem;int opt;LMSystem.Menu();do{printf("Menu->Option: ");scanf("%d",&opt);getchar();switch(opt){case 0: break;case 1: LMSystem.AddBook(); break;case 2: LMSystem.LendBook(); break;case 3: LMSystem.ReturnBook(); break;case 4: LMSystem.EraseBook(); break;case 5: LMSystem.OutputBooks(); break;case 6: LMSystem.OutputReaders(); break;case 7: LMSystem.TestMode(); break;default: printf("ERROR: Wrong command, try again... \n"); break;}//switch(opt)}while(opt);return 0; }

    頭一次寫文章難免有些紕漏,還望各位指正。


  • 二叉搜索樹,平衡二叉樹,紅黑樹的算法效率 ??

  • 艾茲格·W·迪科斯徹 (Edsger Wybe Dijkstra,1930年5月11日~2002年8月6日) ??

  • 總結

    以上是生活随笔為你收集整理的一种基于平衡二叉树(AVL树)插入、查找和删除的简易图书管理系统的全部內容,希望文章能夠幫你解決所遇到的問題。

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

    主站蜘蛛池模板: 日本一级免费视频 | 婷婷综合五月 | aa黄色大片 | 欧美精品一区二区三区视频 | www国产www| 日韩欧美一区二区三区在线 | 很黄很色的视频 | 91精品在线看 | 国产精品一区二区三区四区 | 经典杯子蛋糕日剧在线观看免费 | 欧美日本在线视频 | 超级黄色录像 | 久操视频免费 | 97超视频在线观看 | 成人羞羞国产免费游戏 | 欧美激情在线 | 成人在线观看你懂的 | 国产精品亚洲天堂 | 国产精品久久久久久中文字 | 久久久久99精品成人片 | 男女av| 中文字幕一区二区三区人妻四季 | 麻豆视频国产精品 | 日韩精品美女 | 欧美性大战久久久久xxx | 天天看黄色 | 国产黄色美女视频 | 精东传媒在线观看 | 蜜桃导航-精品导航 | 波多野结衣免费看 | 福利在线免费 | 亚洲一本在线 | 国产黄a三级三级三级看三级男男 | 日本黄网在线观看 | 亚洲涩涩网 | 亚洲激情视频网站 | 少妇又色又紧又黄又刺激免费 | 亚洲一区视频在线播放 | 天堂中文网在线 | 色噜噜狠狠一区二区三区 | 国产系列在线观看 | 天堂在线视频观看 | 久久人妻少妇嫩草av无码专区 | 国产精品久久久久久久久久久久久久 | 美女xx网站 | 亚洲av女人18毛片水真多 | 欧美日韩成人一区二区 | 欧美不卡网 | 久久久精品中文字幕 | 国产一区二区三区四区在线观看 | 日韩乱码人妻无码系列中文字幕 | 性xxx法国hd极品 | 日韩精品一区二区三区中文在线 | 午夜之声l性8电台lx8电台 | 亚洲天堂免费在线观看视频 | 久久三级网| 韩国三级hd中文字幕 | 亚洲精品国产精华液 | 一级免费观看视频 | 人人超碰人人 | 黄色一级网站 | 国产aaaaa毛片 | 色噜噜综合网 | 视色视频在线观看 | 精品动漫一区二区三区的观看方式 | 欧美亚洲一区 | 久久精品国产亚洲av麻豆图片 | 亚洲精品激情 | 欧美黑人一区 | 色婷婷伊人| 中文字幕成人一区 | 女女h百合无遮羞羞漫画软件 | 美女被出白浆 | 高清不卡一区二区三区 | 西西4444www大胆无码 | 深夜网站在线观看 | 91资源在线视频 | 亚洲永久在线 | 少妇特黄a一区二区三区 | 成年人福利网站 | 精品国产一区二区三区久久久 | 欧美视频xxxx | 一区二区三区欧美视频 | www.三级.com| 丝袜 亚洲 另类 国产 制服 | 欧美日韩一卡二卡 | a√国产 | 妞妞影视| 国产www在线| 免费污污视频在线观看 | 国产精品久久久久无码av色戒 | www.日韩.com | 久久久久久久久久久久久国产 | 小向美奈子在线观看 | 久久久无码精品亚洲无少妇 | 五月激情在线 | 国产中文在线播放 | 91干干| cao我|