C++建立动态链表


#include<iostream>
#include<string>
using namespace std;
class book
{
public:
int num;
double price;
book* next;
};
bool check(string str)
{
for(int i=0;i<str.length();i++)
{
   if((str[i]>'9'||str[i]<'0')&&(str[i]!='.'))
    return false;
}
return true;
}

book* create()
{
book *p1,*p2=NULL,*head=NULL;
p1=new book;
head=p1;
p2=p1;
cout<<"please enter number of book,then 0 to end:\n";
string str_num,str_price;
cin>>str_num;
while(!check(str_num))
{cout<<"the enter of your is error,please enter true number:\n";cin>>str_num;}
p1->num=atoi(str_num.c_str());
if(p1->num==0)
{
   delete p1;p2->next=NULL;p2=NULL;head=NULL;cout<<"p1->num=0\n";return head;
}
while(p1->num!=0)
{
   cout<<"please enter price of the book:\n";
   cin>>str_price;
   while(!check(str_price))
   {cout<<"the enter of your is error;please enter true number:\n";cin>>str_price;}
   p1->price=atof(str_price.c_str());
   p2=p1;
   p1=new book;
   p2->next=p1;
   cout<<"please enter number of book,then 0 to end:\n";
   cin>>str_num;
   while(!check(str_num))
   {cout<<"the enter of your is error;please enter true number:\n";cin>>str_num;}
   p1->num=atoi(str_num.c_str());
   cout<<p1->num;
}
delete p1;
p2->next=NULL;
return head;
}

void print(book* head)
{
book* p;
p=head;
cout<<"num"<<"\t"<<"price"<<"\n";
while(p)
{
   cout<<p->num<<"\t"<<p->price<<"\n";
   p=p->next;
}
delete p;
}


int main()
{
book* head=NULL;
head=create();
print(head);
delete head;
return 0;
}

相关内容