【问题标题】:Linked list implementation in c, run time errorc中的链表实现,运行时错误
【发布时间】:2017-06-28 19:48:41
【问题描述】:

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

#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;
}

【问题讨论】:

  • 为了便于阅读和理解:: 1) 单独的代码块(for、if、else、while、do...while、switch、case、default)通过一个空行 2) 跟随公理:每行只有一个语句,并且(最多)每个语句一个变量声明。
  • 在调用scanf()时,一定要检查返回值(不是参数值),确保操作成功。
  • 在调用任何堆分配函数(malloc、calloc、realloc)时,1) 始终检查 (!=NULL) 返回值以确保操作成功。 2) 返回类型为void*,因此可以分配给任何指针。强制转换只会使代码混乱,使其更难以理解、调试等。

标签: c pointers data-structures linked-list singly-linked-list


【解决方案1】:

也许有一些逻辑错误?

是的!

这里:

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

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

尝试这样做:

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

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


PS:Do I cast the result of malloc?不!

【讨论】:

  • while(temp!=NULL){temp=temp->next;} temp=new_node;这行得通。
  • @EshanPandey 我认为您应该遵循我的解决方案,因为我测试它运行良好。您的方法没有连接节点。
  • 并不是我不喜欢你的解决方案,只是我想出了自己的解决方案。显然,您的回答有所帮助。你指出我做错了什么,这对我有帮助。 @gsamaras 谢谢。顺便说一句,仍在为 print() 函数苦苦挣扎。
  • 是的,因为您不链接节点。你的每个节点的next 成员在你的解决方案中指向NULL,而在我的解决方案中,每个节点都指向它的下一个节点。这就是为什么你不能打印你的名单@EshanPandey。
  • 是的,我认为你是对的。我的方法没有连接节点,因此没有打印整个列表..只有第一个元素。但我不完全理解这一点。你能帮忙(解释一下)
猜你喜欢
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多