c - Visual Studio 突然停止工作(链接列表代码)

标签 c visual-studio-2012 linked-list

每一个 我在使用链接列表函数时遇到问题。 Visual Studio 突然停止工作。以下是我的代码:

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

typedef struct _listnode
{
int item;
struct _listnode* next;
}Listnode;

void printlist(Listnode *head);
void main(){
Listnode *head, *temp;
int i = 0;
head = malloc(sizeof(Listnode));
temp = head;
for(;i<3;i++){
    temp->item = i;
    if (i != 2){
        temp->next = malloc(sizeof(Listnode));
        temp = temp->next;
    }
    else
        temp = NULL;
}
printlist(head);
    }
    void printlist(Listnode *head){
if (head == NULL)
    printf("Your list is empty");
while(head != NULL){
    printf(" %d ",head->item);
    head = head->next;
}
printf(" \n ");
    }

    Output: 
    0 1 2 

然后它显示了以下消息 enter image description here

谁能告诉我到底发生了什么事吗?任何帮助将不胜感激。谢谢

最诚挚的问候

最佳答案

创建列表时,永远不要将最终链接指针设置为 NULL。当您想将 temp->next 设置为 null 时,您将 temp 设置为 null。

在每次交易后将列表保持在有效状态会更加“稳健”。现在,您依靠循环内的 if 语句将最后一次迭代转换为“结束列表”操作,而不是“添加到列表”。如果有人要更改 for 循环限制而不更改 if 语句以进行匹配,那么您将再次回到损坏的列表。尝试这样的事情:

Listnode *head = NULL; /* start with an empty list */
Listnode *tail = NULL;  

for (i=0; i<3; ++i)
{
    ListNode *temp = malloc(sizeof(Listnode));
    temp->item = i;
    temp->next = NULL;
    if (head == NULL)
        head = tail = temp;
    else
    {
        tail->next = temp;
        tail = temp;
    }
}

循环中仍然有一个 if 语句,但它具有指导意义。循环体是您编写函数以将新列表条目推送到单链表末尾的方式。保留头指针和尾指针可以提高效率,避免循环查找列表末尾。

重点是,无论循环如何修改,循环每次迭代都会添加一个条目,并且列表在每次迭代结束时都有效。

关于c - Visual Studio 突然停止工作(链接列表代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672625/

相关文章:

c - 在 C 程序中将文件中的换行符读取为 char

c - 我试图使用 for 循环找到素数 1-n

c++ - 什么可以解释调用 free() 时的堆损坏?

linked-list - Ocaml双链表: remove a node satisfying a condition from a double linked list

java - 链表实际上是如何改变的

c++ - C/C++ Unix配置文件库

c++ - 使用 Visual Studio 2012 时 OpenGL 的调试问题

visual-studio - 乌龟SVN : new items not added to project

asp.net - 快速撤消意外事件生成

linked-list - 没有 malloc 的 no_std 中的无堆链表