0

I have following code to insert an element in LinkedList. I havebeen following tutorials and I am unable to spot error in this code.

I am using DEVC++ and it gives me a compile time error that says: [Error] 'Node' undeclared (first use in this function)

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

struct Node{
 int data;
 struct Node* next;
};
struct Node* head;  //global variable
int main(){
    head = NULL;  //empty list
    int n, i, x;
    printf("How many numbers would you like to enter");
    scanf("%d", &n);
    for(i=0; i<n; i++){
        printf("Enter the number you want to add to list:");
        scanf("%d", &x);
        Insert(x);
        Print();
    }
}


void Insert(int x){
Node* temp= (Node*)malloc(sizeof(struct Node)); //I get error here
temp->data = x;
//temp->next = NULL; //redundant
//if(head!= NULL){
temp->next = head;  //temp.next will point to null when head is null nd otherwise what head was pointing to
//}
head = temp;
}

void Print(){
    struct Node* temp1 = head;  //we dont want tomodify head so store it in atemp. bariable and then traverse
    while(temp1 != NULL){
         printf(" %d", temp1->data);
         temp1= temp1->next;
    }
    printf("\n");
} 
simar kaur
  • 211
  • 3
  • 7
  • 14
  • 2
    Change `Node* temp= (Node*)malloc(sizeof(struct Node));` to `struct Node* temp= malloc(sizeof(struct Node));` and `temp1= temp1.next` is missing a `;` at the end. – Spikatrix Apr 26 '15 at 06:19
  • Solved the problem. Thanks – simar kaur Apr 26 '15 at 06:21
  • possible duplicate of [Undeclared identifiers with structs](http://stackoverflow.com/questions/20182825/undeclared-identifiers-with-structs) – Ayushi Jha Apr 26 '15 at 06:27

2 Answers2

1

Change Node* temp= (Node*)malloc(sizeof(struct Node)) to struct Node* temp = (struct Node*)malloc(sizeof(struct Node))

Alsty
  • 817
  • 10
  • 23
-1

Create a more modular link list library...your program is less readable..moreover use typedef as much as possible when using structure in c..that will give you more rights to use NODE* instead of struct NODE* every time...

Mayukh Sarkar
  • 2,289
  • 1
  • 14
  • 38