c - 无法在Linux中使用C创建链表

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

我已经用 C++ for Windows 编写了一段类似的代码,其中创建了一个基本的单链表、添加数据并显示列表的内容。这次我尝试用 C 为 Linux 编写一个类似的程序。似乎没有编译器错误或运行时错误,但是当我尝试调用函数 void insert() 时,程序控制台告诉我存在段错误。

我的代码包含在下面:

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

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

nPtr head = NULL;
nPtr cur = NULL;
void insert(int Data);
void display();

int main(void)
{
    int opr, data;

    while (opr != 3)
    {
        printf("Choose operation on List. \n\n1. New Node. \n2. Display List.\n\n>>>");
        scanf("%d", opr);

        switch (opr)
        {
            case 1 :
                printf("Enter data.\n");
                scanf("%d", data);

                insert(data);
                break;

            case 2 :
                display();
                break;

            case 3 :
                exit(0);

            default :
                printf("Invalid value.");
        }
    }

    getchar();
}

void insert(int Data)
{
    nPtr n = (nPtr) malloc(sizeof(nPtr));

    if (n == NULL)
    {
        printf("Empty List.\n");
    }

    n->data = Data;
    n->next = NULL;

    if(head != NULL)
    {
        cur= head;
        while (cur->next != NULL)
        {
            cur = cur->next;
        }
        cur->next = n;
    }
    else
    {
        head = n;
    }
}

void display()
{
    struct Node* n;

    system("clear");
    printf("List contains : \n\n");

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

当我运行代码时,似乎没有任何问题或错误。但是当我调用我在那里创建的两个函数中的任何一个时,出现一个错误,提示“段错误”。我认为 void insert() 中的 malloc() 函数会出现问题,但我无法确定 void 中的问题所在display() 方法。

最佳答案

display() 函数从不初始化n。声明应该是:

nPtr n = head;

关于c - 无法在Linux中使用C创建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59954772/

相关文章:

c - 生成一个没有给定数字的随机数

java - 为什么二叉堆是树结构?

java - 从日志文件中读取 1 TB 的数据

javascript - 为什么 Javascript 数组可以同时保存多种数据类型?

c - 从链接列表中删除单个学生

GTK+ 中的 CSS 不起作用

c - 按字母顺序对 C 中的字符指针数组进行排序时出现段错误

c - 在 C 中向内存写入和读取不同类型

java - 排序算法中的程序中断 block

C 循环跳转到链表开头