171211—链表书写&对类(book题)的润色

来源:互联网 发布:展会erp系统源码 编辑:程序博客网 时间:2024/05/22 14:04

一.
链表不知道是啥时候的事情了,之前自己看完书上例题后,按着自己理解的思路试着写了个链表。
每次都在三个之后停止运行。
调试后有:
这里写图片描述
之前用手画模拟流程的时候没找出明显错误。今天干脆再试一次。最后发现问题出在这里:
这里写图片描述
在第一次(头指针找到第一个链节,且s生成第二环时),第一节的next指针是没有指向的,即p->next无物所指。实际上从第一节开始,这个链表就已经断掉了。
(第一次执行“p=p->next”就乱掉了)
修改后代码如下:

int main(){        struct node    {        int data;        node *next;    };    node *head=NULL,*p,*s;    s=new node;    cout<<"Please cin the data:";    cin>>s->data;    while(s->data!=0)    {        if(head==NULL)         {            head=s;            p=s;        }          else        {            p=p->next;        }        s=new node; //生成新结点并存储数据。         p->next=s;        cout<<"Please cin the data:";        cin>>s->data;    }    p->next=NULL;    delete s;     s=head;    while(s!=0)    {        cout<<s->data<<'\t';        s=s->next;    }    cout<<endl;}

二.类。
给之前单薄的图书借还管理加了点友好化的东西。但还是很鸡肋,不能创建和管理多种图书,不能查找

#include<iostream>#include<cstring>using namespace std;class Book{  public:    //Book(char *p,double price,int number)  //怎么把书名输进去???     //{      //}  z暂时看着不行     Book(char bookname[],double price,int number)     {        strcpy(this->bookname,bookname);    //解决书名的传递赋值问题。         this->price=price;        this->number=number;     }        void display()    {        cout<<"书目:《"<<this->bookname<<"》"<<endl;        cout<<"当前剩余"<<this->number<<"本"<<endl;     }     void borrow()    {        this->number--;        cout<<"书目:《"<<this->bookname<<"》"<<endl;        cout<<"当前剩余"<<this->number<<"本"<<endl;    }    void restore()    {        this->number++;        cout<<"书目:《"<<this->bookname<<"》"<<endl;        cout<<"当前剩余"<<this->number<<"本"<<endl;    }  private:    char bookname[100];    double price;    int number;};int main(){    char name[]={"Sherlockhomles"};    Book One(name,100,40);    One.display();    cout<<"借书请按1;归还请按2;退出请按0."<<endl;    int n;    cin>>n;  //就是说,如果我想实现多次输入的一个功能,我不一定要全打包在while循环里,我完全可以在其前放一个单独的,用来启动的。     while(n)    {      if(n==1||n==2)      {              switch(n)        {          case 1:  One.borrow();break;          case 2:  One.restore();break;        }               cin>>n;      }      else      {         cout<<"请不要调戏可怜的计算机系统哦~请输入0,1或2.退出请按0"<<endl;         cin>>n;      }    }    cout<<"欢迎再次使用本系统。"<<endl;  } 

P.S. 昨日协会培训,于C++学习的最大感悟是,字符串的相关知识真的太重要太重要。要再好好看看。

原创粉丝点击