##最近作业里有一题要用链表,但是上学期老师直接略过链表没讲。。于是只好自学了一下。。照着书上打了代码,按照题目要求修改了一下,却遇到了一些奇怪的问题,实在想不清楚,希望大噶一起康康 万分感谢 下面是题目,IDE用的是CodeBlocks。
#3、建立一个单向链表,每个节点都是某本书的数据,包括:编号ID、书名BookName、作者Author、出版社Publisher。实现图书的管理功能,即实现该链表的数据显示、插入数据、删除数据等功能。
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using std::cout;
using std::endl;
using std::string;
using std::cin;
struct node
{
    int ID;
    string BookName;
    string Author;
    string Publisher;
    struct node *next;
};
int main()
{
    struct node *head,*p,*q,*t;
    int i,n,a;
    string b,c,d;
    cin>>n;
    head =NULL;
    for(i=1;i<=n;i++)
    {
        cin>>a>>b>>c>>d;
        p=(struct node*)malloc(sizeof(struct node));
        p->ID=a;
        p->BookName=b;
        p->Author=c;
        p->Publisher=d;
        p->next=NULL;
        if(head==NULL)
            head=p;
        else
            q->next=p;
        q=p;
    }
    t=head;
    while(t!=NULL)
    {
        cout<<t->ID<<" "<<t->BookName<<" "<<t->Author<<" "<<t->Publisher<<endl;
        t=t->next;
    }
fflush(stdin);
    cin>>a>>b>>c>>d;
    t=head;
    while(t!=NULL)
    {
        if(t->ID==250||t->next==NULL)
        {
        p=(struct node*)malloc(sizeof(struct node));
        p->next=t->next;
        p->ID=a;
        p->BookName=b;
        p->Author=c;
        p->Publisher=d;
        t->next=p;
        break;
        }
        t=t->next;
    }
    t=head;
     while(t!=NULL)
    {
        cout<<t->ID<<" "<<t->BookName<<" "<<t->Author<<" "<<t->Publisher<<endl;
        t=t->next;
    }
    t=head;
    while(t!=NULL)
    {
           if(t->ID==250||t->next==NULL)
           {
               p=t->next;
               t->next=p->next;
               p=NULL;
           }
    t=t->next;
    }
           t=head;
           while(t!=NULL)
    {
        cout<<t->ID<<" "<<t->BookName<<" "<<t->Author<<" "<<t->Publisher<<endl;
        t=t->next;
    }
    return 0;
}
我发现 只有开始输入两组数据以内才能cout出来,而要想完成后面的插入数据,删除数据,只有开始输入一组数据才能运行,如果输入两组以上的数据就会直接崩溃。。。
像这样开始输入一组成功运行
1
250 z zx a
250 z zx a
3 s c k
250 z zx a
3 s c k
250 z zx a
Process returned 0 (0x0)   execution time : 15.775 s
Press any key to continue.
输入两组数据时就无法完成后面的插入数据,删除数据直接报错了,一组数据能正常运行说明代码应该是没问题的,那么问题到底出在哪呢。。。
2
250 s xc e
3 d zx e
250 s xc e
3 d zx e
4 s c r
Process returned -1073741819 (0xC0000005)   execution time : 28.844 s
Press any key to continue.
开始输入三组数据就直接一开始的输出也输出不了了?