链表求助!
下面的代码主要目的是实现求反序对的数目
例如: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。
[解决办法]
#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;}