c - 在单链表末尾插入一个元素

标签 c linked-list

从早上起我就一直在尝试修复此代码,但可以完成。所以,最后我需要一些帮助来找出错误。代码编译时没有错误,但是当我从终端运行它时,我收到一条错误消息“段错误:11”

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


struct Node{
    int data; 
    struct Node *next; 
};


struct Node *head; 


void Insert(int data); 
void Print();  


int main()
{
    head = NULL; //list is empty

    Insert(3); 
    Insert(5); 
    Insert(2); 
    Insert(8); 

    Print(); 

    return 0;  
} 


void Insert(int data) 
{
    struct Node *temp = malloc(sizeof(struct Node)); 

    temp->data = data; 
    temp->next = NULL; 

    struct Node *temp1 = head;

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

    temp1->next = temp; 
}


void Print()
{ 
    struct Node *temp =head; 

    while(temp != NULL)
    { 
        temp = temp->next; 
        printf("%d", temp->data); 
    } 
}

最佳答案

  1. 您绝不能将 head 设置为 NULL 以外的任何值。

  2. (即使您修复了上述问题)当您到达 temp1->next = temp; 时,temp1 也保证为 NULL .

附注我不认为将变量称为 temptemp1 等是一个很好的做法。从这些名称中不可能看出它们的功能是什么。

关于c - 在单链表末尾插入一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193712/

相关文章:

使用 arm-eabi-gcc 交叉编译模块

c - 字符串指针问题,未正确指向

c - 错误 : conflicting types for ‘whatever’

C、双向链表问题

c - 如何从堆内存数组 INSIDE STRUCT 写入?

代码漏洞

c++ - 双向链表,按顺序添加节点

c++ - 如何在 C++ 的链表中创建前一个指针?

c - C 中的链表段错误

java - java 中的双端队列实现中我的类型未定义方法