首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

链表

2012-02-06 
链表求助!下面的代码主要目的是实现求反序对的数目例如:1,2,3,4,5那么反序对的数目就是05,1,2,3,4的反序对

链表求助!
下面的代码主要目的是实现求反序对的数目
例如:1,2,3,4,5那么反序对的数目就是0
5,1,2,3,4的反序对的数目就是4,因为5比后面的都大,下面的代码有什么错啊,我是菜鸟,请大家指点一下

#include <string>
#include <iostream>
using namespace std;
static int reverse_count=0;
struct Node 
{
int data;
struct Node *next;
};
int main()
{
int array_1[5]={5,1,2,3,4};
struct Node *p,*q,*r,*Head;
p=(struct Node *)malloc(sizeof(struct Node *));
p->data=array_1[0];
cout<<p->data<<endl;
Head=(struct Node *)malloc(sizeof(struct Node *));
Head->next=p;
cout<<Head->next->data<<std::endl;
for(int i=1;i<5;i++)
{
r=(struct Node *)malloc(sizeof(struct Node *));
q=(struct Node *)malloc(sizeof(struct Node *));
r=Head;
q=r->next;
q->next=NULL;
while(array_1[i]<q->data && q!=NULL )
{
r=r->next;
q=q->next;
reverse_count++;
}
p=(struct Node *)malloc(sizeof(struct Node *));
p->data=array_1[i];
r->next=p;
p->next=q;
q->next=NULL;

}

cout<<reverse_count<<endl;
return 0;
}

[解决办法]
sizeof(struct Node *) // 修改为 sizeof(struct Node),其他有没有错误,没看。
[解决办法]
搜索了下,好像代码里确实没有 free。
[解决办法]

探讨

sizeof(struct Node *) // 修改为 sizeof(struct Node),其他有没有错误,没看。

[解决办法]
探讨
引用:
sizeof(struct Node *) // 修改为 sizeof(struct Node),其他有没有错误,没看。


这个应该没有错误吧,它本身就是一个指针类型,当然要sizeof(struct Node *)了啊

[解决办法]
C/C++ code
#include <string>#include <iostream>using namespace std;static int reverse_count=0;struct Node  {    int data;    struct Node *next;};int main(){    int array_1[5]={5,1,2,3,4};    struct Node *p,*q,*r,*Head,*p1;    p=(struct Node *)malloc(sizeof(struct Node ));    p1=(struct Node *)malloc(sizeof(struct Node ));    p = p1;    for( int k =0;k < sizeof(array_1)/sizeof( int ); k++ )    {        p1->data = array_1[k];        p1 = p1->next = (struct Node *)malloc(sizeof(struct Node ));    }    //cout<<p->data<<endl;    Head=(struct Node *)malloc(sizeof(struct Node));    Head->next=p;    //cout<<Head->next->next->data<<std::endl;    for(int i=1;i<5;i++)    {        r=(struct Node *)malloc(sizeof(struct Node ));        q=(struct Node *)malloc(sizeof(struct Node ));        r=Head;        q=r->next;        while(array_1[i]<q->data && q!=NULL )        {            r=r->next;            q=q->next;            reverse_count++;        }        p=(struct Node *)malloc(sizeof(struct Node *));        p->data=array_1[i];        r->next=p;        p->next=q;        q->next=NULL;    }    cout<<reverse_count<<endl;    return 0;} 

热点排行