Hi,
I'm learning C++ via a tutorial both with the book and the video. I transcribed the following programme there.
I have the questions as below:
Q1: I don't understand why the tutor assigned p1 to p2 in the Line 16 of fuction create, before going to "while". I think that is redundant because it just creates a node so far.
I remove "p2=p1"from Line 16, and "p2=NULL" from Line 26 , and the result seems same when I run the programme.
Could you please explain why the tutor needed to assigned p1 to p2 before going to "while"?
Q2: In his book he wrote" book* create", but on the video he typed "book*create".
Are they identically same?
Q3: In the book he set "main" as void, but on the video he set "main" to return an int.
Are they alternative?
Many thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include<iostream>
using namespace std;
class book
{
public:
int num;
float price;
book *next;
};
book *head=NULL;
book* create()
{
book *p1, *p2;
p1=new book;
head=p1;
p2=p1;
cout<<"Please input book number. It ends with the input of 0"<<endl;
cin>>p1->num;
if(p1->num!=0)
{
cout<<"Please input book price."<<endl;
cin>>p1->price;
}
else
{
delete p1; p2=NULL; head=NULL; return head;
}
while(p1->num!=0)
{
p2=p1;
p1=new book;
cout<<"Please input book number. It ends with the input of 0"<<endl;;
cin>>p1->num;
if(p1->num!=0)
{
cout<<"Please input book price."<<endl;
cin>>p1->price;
}
p2->next=p1;
}
delete p1;
p2->next=NULL;
return head;
}
int main()
{
create();
return 0;
}
|