在链接列表中删除?

时间:2014-06-21 13:54:06

标签: c linked-list

我写了以下代码:

#include<stdio.h>

struct student{
char name[25];
double gpa;
struct student *next;
};

struct student *list_head;

struct student *create_new_student(char nm[], double gpa) 
{
         struct student *st;
         printf("\tcreating node\t");
         printf("\nName=%s \t Gpa= %.2f\n", nm, gpa);

         st = (struct student*)malloc(sizeof (struct student ));
         strcpy(st->name, nm);
         st->gpa = gpa;
         st->next = NULL;
         return st;
}

void printstudent(struct student *st) 
{
         printf("\nName %s,GPA %f\n", st->name, st->gpa);
}

void insert_first_list(struct student *new_node) 
{
         printf("\nInserting node: ");
         printstudent(new_node);
         new_node->next = list_head;
         list_head = new_node;
}

struct student *delete_first_node() 
{
         struct student *deleted_node;
         printf("\nDeleting node: ");
         printstudent(deleted_node);
         list_head = list_head->next;
         return deleted_node;
}

void printlist(struct student *st)
{
         printf("\nPrinting list: ");
         while(st != NULL) {
             printstudent(st);
             st = st->next;
         }
}

int main() 
{
         struct student *other;
         list_head = create_new_student("Adil", 3.1);
         other = create_new_student("Fatima", 3.8);
         insert_first_list(other);
         printlist(list_head);
         other = delete_first_node();
         printlist(list_head);
         return 0;
}

当我运行它时,没有错误或警告。但是,它会在删除部分停止。消息显示程序已停止工作。

你能帮我找到问题吗?

1 个答案:

答案 0 :(得分:1)

在函数delete_first_node中,节点deleted_node未初始化并传递给尝试访问其成员的函数printstudent,导致未定义的行为。 /> 该功能应该是

struct student *delete_first_node(){
    struct student *deleted_node = list_head;
    printf("\nDeleting node: ");
    if(deleted_node != NULL)
    {
        printstudent(deleted_node);
        list_head= list_head->next;
        free(deleted_node);
    }
    else
       printf("List is emty\n");

    return list_head;
}