roshannepal_x
roshannepal_x

Reputation: 71

i can't find error in this 'Inserting node at begining of list' using singaly linked list

I did this code with the help of code on Youtube/freeCodeCamp.org/data structure -using C and C++. Same code worked for tutor ,but in my PC it is not working.

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

struct Node
{          
    int data;   
    struct Node *next; 
};
struct Node *head;
void Insert(int x)
{
    struct Node *temp = (Node *)malloc(sizeof(struct Node));
    (*temp).data = x;
    (*temp).next = head;
    head = temp;
};
void Print()
{
    struct Node *temp = head;
    printf("List is::");
    while (temp != NULL)
    {
        printf("%d", temp->data);
        temp = temp->next;
    }
    printf("\n");
};
int main()
{
    head = NULL;
    printf("How many numbers;\n");
    int n, x;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        printf("Enter the number;\n");
        scanf("%d", &x);
        Insert(x);
        Print();
    }
}

Compiler output:

insertingNodeAtbegining.c: In function 'Insert':
insertingNodeAtbegining.c:12:26: error: 'Node' undeclared (first use in this function)
     struct Node *temp = (Node *)malloc(sizeof(struct Node));
                          ^~~~
insertingNodeAtbegining.c:12:26: note: each undeclared identifier is reported only once for each 
function it appears in
insertingNodeAtbegining.c:12:32: error: expected expression before ')' token
     struct Node *temp = (Node *)malloc(sizeof(struct Node));
                                ^

Upvotes: 0

Views: 63

Answers (2)

Tejaswini Ramakrishna
Tejaswini Ramakrishna

Reputation: 24

please add the data type struct in the 12th line, i.e.

struct Node *temp = (struct Node *)malloc(sizeof(struct Node));

Thank you for this question.

Upvotes: 1

Sanket Bhurke
Sanket Bhurke

Reputation: 15

Same code worked for the tutor because he used C++ compiler and in your case you are using c compiler.

For compiling with c compiler modify line 12 as follows.

struct Node *temp = (struct Node *)malloc(sizeof(struct Node));

In C, you have to use struct keyword whenever you are declaring struct data type. That is not the case with C++.

Upvotes: 0

Related Questions