【发布时间】:2017-01-04 03:53:59
【问题描述】:
我还是编程新手。我只是想问我如何使用指针进行线性搜索。我想制作一个图书管理程序,并且我制作了一个带有指针的程序。
This is the example of how i want it.
这是编码
#include <iostream>
#define MAX 5
using namespace std;
struct record
{
int id;//stores id
float price;//store price
int qty;//stores quantity
record* next;//reference to the next node
};
record* head;//create empty record
record* tail;//the end of the record
void push(record *& head, record *&tail, int id, float price, int qty)
{
if (head == NULL)
{
record* r = new record;
r->id = id;
r->price = price;
r->qty = qty;
r->next = NULL;//end of the list
head = r;
tail = r;
}
else if (head != NULL && (MAX - 1))
{
record* r = new record;
r->id = id;
r->price = price;
r->qty = qty;
r->next = head;
head = r;
}
}
int pop(record *&head, record *& tail)
{
if (head == NULL)
{
cout << "No record in memory" << endl;
}
else if (head == tail)
{
cout << "The record "<<"ID: " << head->id << "\nPrice: " << head->price << "\nQuantity: " << head->qty << "\n" << "was deleted" << endl; //CORRECTION HERE
}
else
{
record* delptr = new record;
delptr = head;
head = head->next;
cout << "The record " << delptr->id << ", " << delptr->price << ", " << delptr->qty << " was deleted" << endl; //CORRECTION HERE
delete delptr;
}
return 0;
}
void display(record *&head)
{
record* temp = new record; //CORRECTION HERE
temp = head;
if (temp == NULL)
{
cout << "No record in memory" << endl;
}
else
{
cout << "Record : " << endl;
while (temp != NULL)
{
cout <<"\nID: "<< temp->id << "\nPrice: " << temp->price << "\nQuantity: " << temp->qty <<"\n"<< endl; //CORRECTION HERE
temp = temp->next;
}
}
}
int LinearSearch(record *&head) {
}
char menu()
{
char choice;
cout << "\t::MENU::\n" << endl;
cout << "1. Add new record\n" << endl;
cout << "2. Delete record\n" << endl;
cout << "3. Show record\n" << endl;
cout << "4. Quit\n" << endl;
cout << "-----------------------\n" << endl;
cout << "\nEnter selection : " << endl;
cin >> choice;
return choice;
}
int main()
{
record* head;
record* tail;
head = NULL;
tail = NULL;
char choice;
do
{
cout << "---------------------- - \n" << endl;
choice = menu();
switch (choice) { //CORRECTION HERE
case '1':
int id, qty;
float price;
cout << "Enter ID:";
cin >> id; // Please correct yourself here, what is r here, r is not declared anywhere
cout << "\nEnter Price: ";
cin >> price;
cout << "\nEnter Quantity: ";
cin >> qty;
push(head, tail, id, price, qty);
break;
case '2':
pop(head, tail);
break;
case'3':
display(head);
break;
default:
cout << "Quiting...\n";
}
} while (choice != '4');
return 0;
}
如何为这种编码编写指针代码的线性搜索?我尝试在整个网络上查找示例,但当我执行它时,它不起作用,所以我将其留空。
【问题讨论】:
-
线性搜索就是遍历链表。请阅读更多相关信息并尝试实施。
-
我建议使用标准容器。向量或列表。然后您将拥有可以使用的查找功能。
-
同意保罗。首先使用预定义的数据结构学习(C++)编程的基础知识。您需要自己学习实现数据结构的指针,但那时您应该已经精通使用数据结构。