简体   繁体   中英

Insert a node to last position in a LinkedList

I need to insert a node to the last position of a linked list. This is what I came up with:

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

struct node { float data;
                struct node * next;
};

struct node* makenode(float item){
    struct node* p=(struct node*)malloc(sizeof (struct node));
    if(p) p->data = item;
    return p;
}
void init (struct node **p){
    *p=0;
}
int addlast(struct node **ptr, float item){
    struct node* p=makenode(item);
    if(!p) return 0;
    struct node* temp=*ptr;
    while(temp->next)temp = temp->next;
    p->next=0;
    temp->next=p;
    return 1;
}      
float delfirst(struct node **ptr){
    struct node* p =*ptr;
    *ptr=(*ptr)->next;
    float temp=p->data;
    free(p);
    return temp;
}

void main(){
    struct node *list,*list2;
    init (&list);
    int i;

    for(i=0;i<10;i++)addlast(&list,i);

    while(list)printf("%4.2f\t",delfirst(&list));
    getchar();

}

but when I compile my code, its keep getting crashed and the error is in the addlast function. but I can't find where I got wrong. Can anyone please tell me where I got wrong in addlast function?

Your makenode function is flawed, it doesn't initialize all elements in the structure.

Your addlast is also flawed, in that when you're adding the first node then *ptr is NULL and you're dereferencing this NULL pointer in temp->next , leading to undefined behavior .

struct node* temp=*ptr;
while(temp->next)temp = temp->next;

When you call addlast() API your pass a pointer which is NULL and you use this pointer to initialize temp and start using temp.

Accessing/Dereferencing NULL pointers will lead to undefined behavior and hence the crash.

在使用temp->next之前,测试temp是否为NULL。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM