Search code examples
clistlinked-listpointer-to-pointer

linked list implementation using pointer to pointer in C


I am unable to append a new node in the linked list. I have already identified the problem area but after much research and trying many things I am still unable to resolve the issue. The problem is with the for loop in insert_node(char,struct **) function and traverse(struct *) function both of which never seem to terminate:

    // 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);
}

}

Please help!


Solution

  • The problem is inside the insert_node function, specifically with the loop:

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

    You'd be better advised not to use the reference temp in your loop, as it overwrites the head->next back to itself. Create another temporary pointer.