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

标签 c pointers data-structures linked-list 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;
}

最佳答案

Maybe there is some logical error?

是的!

这里:

while(temp!=NULL) { temp=temp->next; }
(*temp).next=new_node;

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

尝试这样做:

while(temp->next != NULL) { temp=temp->next; }

temp 指向列表的 last 节点之前循环。通过该更改,您的代码应该可以正常工作。


附言:Do I cast the result of malloc?不!

关于c - c中的链表实现,运行时报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44811368/

相关文章:

c - 将 C 函数映射到调用堆栈

c++ cout如何打印char*

c - 如何从 C 中的函数返回一个数组?

c++ - vector 、矩阵和四元数的缓存性能

java - 如何在 MySQL 的列中保留 1 和 0 的序列?

c - C 中的高级预处理器标记化

c - 如何修复此 do-while 循环,以便控制台程序在自动关闭之前提示用户?

java - 如何将不同类型的对象添加到 Android 中的 HashMap 中?

c++ - 计算 SLOC GCC C/C++ Linux

C 数组和指针