- 建立連結清單: book *creat()//建立連結清單 { book *head = NULL,*tail=NULL; int _num; float _price; while (1) { cout << "輸入書編号:(-1表示輸入結束)" << endl; cin >> _num; if (_num >= 0) { book *p = new book; p->num = _num; cout << "輸入書價格:(-1表示輸入結束)" << endl; cin >> _price; p->price = _price; //p->next = NULL;//如果在結構體裡沒有預設值,就有這句 if (head==NULL) { head = p; tail = p; } else { tail->next = p; tail = p; } } else if (_num == -1) { return head; } else { cout << "輸入有誤,請重新輸入!" << endl; //待寫 清理緩存區 } } return head; }
- 顯示連結清單: void Show(book *head)//連結清單顯示 { while (head) { cout << "圖書編号:"<<head->num <<" 圖書價格:"<< head->price << endl; head = head->next; } }
- 删除結點 book* Delete(book *head,int num)//(每次删除一個結點)傳回頭結點的指針,因為如果删除了頭結點,就得将删除後的頭結點傳回出來 { book *cur = head; if (head->num==num) { head = head->next; delete cur; cout << "操作成功!" << endl; return head; } while (cur->next) { if (cur->next->num==num) { book *del = cur->next; cur->next = del->next; delete del; cout << "操作成功!" << endl; return head; } else { cur = cur->next; } } cout << "沒找到!" << endl; return head; }
- 插入結點
- 尾插法: book*insert(book *head, int num)//傳回頭結點 因為有可能插在第一個 { book *p = new book,*cur=head; cin >> p->num >> p->price; while (cur->next) { cur = cur->next; } cur->next = p; return head; }
- 頭插法: book*insert(book *head, int num)//傳回頭結點 因為有可能插在第一個 { book *p = new book,*cur=head; cin >> p->num >> p->price; head = p; head->next = cur; return head; }
- 中間插法: book*insert(book *head, int num)//傳回頭結點 因為有可能插在第一個 { book *p = new book,*cur=head; cin >> p->num >> p->price; if (p->num <=head->num)//頭部插入 { head = p; head->next = cur; return head; } while (1) { if (cur->next == NULL)//尾部插入 { cur->next = p; return head; } if (cur->next->num>p->num)//中間插入 { p->next = cur->next; cur->next = p; return head; } cur = cur->next; } }