琏表值传递的问题??????

来源:百度知道 编辑:UC知道 时间:2024/09/22 15:39:13
这是部分代码,实现琏表的顺序插入,按小到大。是值传递错误吗???
帮忙修改一下。
……
typedef struct node{
int n;
string s;
struct node *next;
}dna;
……
dna* insert(string& st,dna *head){
dna *q,*p,*te;
te=(node*)malloc(sizeof(dna*));
q=head;
te->n=sort(st);//sort返回int值
te->s=st;
if(q==NULL){
q->n=te->n;
q->s=te->s;
q->next=NULL;
}
else{
p=head;
while(p!=NULL){
if(p->next==NULL){
p->next=te;
te->next=NULL;
}
else if(te->n>p->n && te->n < p->next->n){
te->next=p->next;
p->next=te;
}
else p=p->next;
}
}
return head;
}
把te=(node*)malloc(sizeof(dna*));
改成
te=(node*)malloc(sizeof(dna));
还是不行。

te=(node*)malloc(sizeof(dna*)); 只分配了一个指针大小的空间吧,在win32环境只有4个字节;
if(p->next==NULL){
p->next=te;
te->next=NULL;

break;//加break,不然会循环插入
}

te=(node*)malloc(sizeof(dna*));

=>
te=(node*)malloc(sizeof(dna));

te=(node*)malloc(sizeof(dna*));/*这句有问题*/
te = (node *)malloc(sizeof(dna));