简体   繁体   English

创建链接列表并打印元素?

[英]Creating Linked List and printing the elements?

I want to create a linked list of numbers from 1 to 1000 and print the numbers. 我想创建一个从1到1000的数字链接列表并打印数字。 Im using the function createList() to create the list and printList() to print the elements. 我使用函数createList()来创建列表,使用printList()来打印元素。 But the following code is crashing. 但是下面的代码崩溃了。 Can anybody please rectify. 任何人都可以纠正。 I'm new to linked list 我是链接列表的新手

#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;
    }
}
void createList()
{
    int i;
    struct node *temp, *loc_head;
    loc_head = head;

    for(i=0;i<10;i++)
    {
        struct node* newnode = malloc(sizeof(struct node));
        newnode->data = i+1;
        newnode->link = NULL;
        if(head == NULL) {
            head=newnode;
            loc_head = newnode;
        }
        else {
            head->link = newnode;
            head = newnode;
        }
    }
    head = loc_head;
}   

don't typecast the result of malloc 不要对malloc的结果进行类型转换

给定一个元素数组,从数组创建一个链表(每个元素一个新节点,使用将节点添加到列表末尾的函数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM