0

I want to create a linked list of numbers from 1 to 1000 and print the numbers. Im using the function createList() to create the list and printList() to print the elements. 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;
}
Kara
  • 6,115
  • 16
  • 50
  • 57
Harish R
  • 65
  • 2
  • 4
  • 11

3 Answers3

3
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;
    }
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0
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

Community
  • 1
  • 1
sujin
  • 2,813
  • 2
  • 21
  • 33
-1

Given an array of elements, create a linked list from the array (one new node per element, using the function that adds nodes to the end of a list).