在C中使用指向指针的指针的链表实现

达克·奈特

我无法在链表中添加新节点。我已经确定了问题所在,但是经过大量研究并尝试了许多事情之后,我仍然无法解决问题。问题在于insert_node(char,struct **)函数和traverse(struct *)函数中的for循环似乎都从未终止过:

    // program that stores name of the user using linkedlist

    #include<stdio.h>
    #include<stdlib.h>

typedef struct LIST{
    int flag;
    char name;
    struct LIST *next;
} LISTNODE;

LISTNODE *head=NULL,*newnode=NULL;// global pointers

LISTNODE* initialize(); //initializes struct node with default values and returns a node
void insertNode(char c,LISTNODE** temp);
void traverselist(LISTNODE *temp);

int main(){
char ans,ch;
printf("\n\nEnter your name and hit enter-\n\n");
do{
printf("your name:");
fflush(stdin);
scanf("%c",&ch);

insertNode(ch,&head);

printf("\n\ninsertnode-back to main()");
printf("Want to continue?(Y?N):");
fflush(stdin);
scanf("%c",&ans);
}while(ans=='y'||ans=='Y');

printf("\n\ntraverselist-leaving main()");

traverselist(head);

printf("\n\ntraverselist-back to main()");
return 0;
}

void insertNode(char c, LISTNODE **temp){

printf("\n\ninto insertnode: before initialize");

LISTNODE* temp2;

newnode=initialize();
printf("\n\nback to insertnode:after initialize");
//printf("\nnewnode->name=%c",newnode->name);
//printf("\nnewnode->flag=%d",newnode->flag);

newnode->name=c;
//printf("\nnewnode->name=%c",newnode->name);
//printf("\nnewnode->flag=%d",newnode->flag);

//for(;(*temp)!=NULL;temp=&(*temp)->next);
/*while((*temp)->next!=NULL){
    temp=&(*temp)->next;
    printf("\n\nIn while!");
}
*/

for(;*temp!=NULL;temp=&((*temp)->next))
    printf("\n\nIn for!") ;

//printf("\n\nout of while!");
(*temp)=newnode;

}

LISTNODE* initialize(){

static int count=0;
LISTNODE *tempnewnode;
printf("\n\nINto inintialize!");
tempnewnode=(LISTNODE*)malloc(sizeof(LISTNODE));
if(tempnewnode==NULL){
    printf("No memory available. Aborting!");
    exit(0);
}
else{
        tempnewnode->flag=0;
        tempnewnode->name='*';
        tempnewnode->next=NULL;
        if(count==0){
            head=tempnewnode;
            count++;
        }
}

return tempnewnode;
}

void traverselist(LISTNODE *temp){
printf("\n");
for(;temp!=NULL;temp=temp->next){

        printf("%c",temp->name);
}

}

请帮忙!

fpga_magik

问题出在insert_node函数内部,特别是在循环中:

for(;*temp!=NULL;temp=&((*temp)->next)) printf("\n\nIn for!");

建议您不要在循环中使用参考温度,因为它会覆盖head-> next本身。创建另一个临时指针。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章