c中的链表实现,运行时错误

Esh*_*dey 1 c pointers linked-list data-structures singly-linked-list

编译代码时没有错误,但程序在两次输入后在运行时崩溃.也许有一些我无法解决的逻辑错误.我试图在链接列表的尾部插入节点,同时只保持头部位置.

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

struct Node{

    int data;
    struct Node* next;
};

struct Node *head;

//print the element of the lists
void print(){
    printf("\nThe list from head to tail is as follows \n");
    struct Node* temp = head;
    while(temp!=NULL){
        printf("\n %d ",(*temp).data);
        temp = (*temp).next;
    }
}

//insert a node at the tail of the linked list
void insert_at_tail(int data){
    struct Node* temp = head;
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data=data;
    new_node->next=NULL;

    if(temp==NULL){
        head=new_node;
    }
    else{
        while(temp!=NULL){temp=temp->next;}
        (*temp).next=new_node;
    }
}
int main(){

    head = NULL;
    int i,data;
    for(i=0;i<5;i++){
        scanf("%d",&data);
        insert_at_tail(data);
    }
    print();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

gsa*_*ras 5

也许有一些逻辑错误?

是!

这里:

while(temp!=NULL) { temp=temp->next; }
(*temp).next=new_node;
Run Code Online (Sandbox Code Playgroud)

你会循环直到temp实际上NULL,然后要求其next成员,所以你所要求nextNULL,所以你是在自找麻烦(程序崩溃)!

尝试这样做:

while(temp->next != NULL) { temp=temp->next; }
Run Code Online (Sandbox Code Playgroud)

循环的位置,直到temp指向列表的最后一个节点.通过该更改,您的代码应该可以正常工作


PS:我是否施放了malloc的结果?没有!