创建链表并打印元素?

标签 c pointers linked-list

我想创建一个从 1 到 1000 的数字链表并打印这些数字。 我使用函数 createList() 创建列表,使用 printList() 打印元素。 但是下面的代码崩溃了。 任何人都可以纠正。我是链表新手

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

struct node
{
int data;
struct node* link;
};

struct node* head;

void deleteNode()
{

}

void createList()
{
    int i;
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    head = temp;
    struct node* temp1 = (struct node*)malloc(sizeof(struct node));
    for(i=0;i<10;i++)
    {
        temp->data = i+1;
        temp->link = temp1;
        temp1->link = temp++;
        temp1++;
    }
}

void printList()
{
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp = head;
    while(temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->link;
    } 
}

int main()
{
    head = NULL;
    createList();
    printList();
    return 0;
}

最佳答案

void createList(){
    int i, size = 10;
    struct node* temp = malloc(sizeof(struct node));
    head = temp;

    for(i=0;i<size;i++){
        temp->data = i+1;
        temp->link = i < size - 1 ? malloc(sizeof(struct node)) : NULL;
        temp = temp->link;
    }
}

void createList(){
    int i, size = 10;
    struct node* temp = malloc(size*sizeof(struct node));
    head = temp;

    if(temp){
        for(i=0;i<size;i++){
            temp->data = i+1;
            temp->link = temp + 1;
            ++temp;
        }
        temp[-1].link = NULL;
    }
}

关于创建链表并打印元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21003205/

相关文章:

C指针处理(基础)

c++ - 在 C/C++ 中读/写半字节(没有位域)

c - C 中的链表插入

c - 如何从文件读入并从缓冲区输出到另一个数组

c++ - 我有一个文本框,我想输入语言 A 的字符串

c - 函数中的指针语法

c++ - 我们可以确定指向的数据是否是手动分配的吗?

c++ - C++(或 C)中关于指针的函数作用域

java - 无法找到两个链表的两种迭代类型之间的区别

c - 制作通用函数将项目加载到链接列表中