链表C++.插入、删除、搜索

Linked List C++. insertion, deletion, search

本文关键字:删除 搜索 插入 C++ 链表      更新时间:2023-10-16

任何建议或指导都将非常棒。。。

  #include <iostream>
  #include <string.h>

  using namespace std;
 struct Book { 
char title[1024];       // Book name
int id;                 // Book id or ISBN number
float price;            // Book price
struct Book* next;
  } *COLLECTION = NULL;
//-- Forward Declaration --// 
void menu(); 
void branching(char option);
void insertion();
void printall();
struct Book* search(); 
void deletion();
void quit(struct Book* HEAD);

 int main()
 {
char ch; 
cout << "nnWelcome to CSE240: Bookstoren";
do {
     menu();
     ch = tolower(getchar()); // read a char, convert to lower case
     cin.ignore();
     branching(ch);
} while (ch != 'q');
return 0; 
}
 void menu()
    {
cout << "nMenu Optionsn";
cout << "------------------------------------------------------n";
cout << "i: Insert a bookn";
cout << "d: Delete a bookn";
cout << "s: Search a bookn";
cout << "p: Review your listn"; 
cout << "q: Quitn";
cout << "nnPlease enter a choice (i, d, s, p, or q) ---> "; 
 }
  void branching(char option)
 {
switch(option)
{
    case 'i':
        insertion();
    break;
    case 'd':
        deletion();
    break;
    case 's':
        search();
    break;
    case 'p':
        printall();
    break;
    case 'q':
        quit(COLLECTION);
        COLLECTION = NULL;
    break;
    default:
        cout << "nError: Invalid Input.  Please try again..."; 
    break;
}
 }

  void insertion()
  {
// add code to insert a new book into the COLLECTION linked list.   
// HINT: You can insert a new book at the beginning of the linked list

 }
  struct Book* search() 
 {    
// add code to search for an existing book in the COLLECTION linked-list
// HINT: If no book matches the tile return a error messag

return NULL;
 }
 void deletion()
 {
// add code to the deletion method. You must call "delete" to remove the object    from the heap.
  }
  void printall()
  {
// Add code to print the book collection.  (HINT: You will need to use a loop.)
  }
  void quit(struct Book* HEAD)
  {
// Add code to delete the objects/books from the lniked-list.
// HINT: Refer to the slides in the homework assignment

   }

我会给你一个insertion()的线索——假设你有一本书要插入

void insertion(Book* newBook)
{
  // The new book will be inserted at the beginning of the linked list,
  // with the original list following on from it
  newBook->next = COLLECTION;
  // The new beginning of the collection should be the new book
  COLLECTION = newBook;
}

对于search(),假设你正在搜索一本具有特定ID 的书

Book* search(int id) 
{
  Book* current = COLLECTION;
  while(current != NULL)
  {
    if(current->id == id)
    {
      // Found it
      return current;
    }
    // Try the next book in the list
    current = current->next;
  }
  // Reached the end, but still could not find the book you are looking for
  return NULL;
}