2014-02-27 129 views
0

在下面的链接列表实现代码中,我收到错误cannot convert node_type to node * for argument 1 to 'node *insert(node *)'。我不明白这个消息。基本上该程序不能从main()调用功能insert链接列表在C中的实现

任何人都可以帮忙解释一下吗?

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

struct node_type 
{ 
    int data; 
    node_type *next; 
}; 

typedef struct node_type node; 

node *insert(node *head); 
void print1(node *temp); 

int main(void){ 
    int dat; 
    char x,ch; 

    node *temp; 


    temp=NULL; 
    printf("do u wanna enter a new node? \n"); 
    scanf("%c", &x); 
    if (x=='y' or x=='Y'){ 

     temp=(node *)malloc(sizeof(node)); 
     printf("enter the data: \n"); 
     scanf("%d ", &dat); 

     temp->data= dat; 
     temp->next = NULL; 
    } 

    printf("do u want to insert another element?\n"); 
    scanf("%c ", &ch); 
    if(ch=='y' or ch=='Y'){ 
     insert(temp); 
    } 
    print1(temp); 

    getch(); 

} 
node *insert(node *temp) 
{ 
    int dat; 
    char ch1; 
    node *newnode; 

    newnode=(node *)malloc(sizeof(node)); 

    printf("enter the data: "); 
    scanf("%d", &dat); 
    newnode->data=dat; 
    newnode->next=temp; 
    temp=newnode; 

    printf("do u want to insert another element?\n"); 
    scanf("%c ", &ch1); 
    if(ch1=='y' or ch1=='Y'){ 
     insert(temp); 
    } 
    else return temp; 

} 
void print1(node *temp) 
{ 
    int t; 

    while(temp!= NULL){ 
     t= temp->data; 
     temp= temp->next; 
     printf(" %d ", t); 
    } 
} 
+1

附加线在严格C,该结构定义将不编译。如果使用C++编译器进行编译,它将进行编译。由于您使用的是'',因此您可能使用了MS Visual C++,我猜你的代码正在编译为C++而不是C。 –

+0

奇怪**错误** –

回答

1

在你的代码的几个问题:

  1. struct node_type

    struct node_type 
    { 
        int data; 
        node_type *next; 
    }; 
    

    的定义根据C语法不正确,类型node_type没有了typedef struct node_type node;语句之前存在。

    为了解决这个问题,你可以

    一)定义struct node_type这样

    struct node_type 
    { 
        int data; 
        struct node_type *next; 
    }; 
    

    B)使用(感谢@yongzhy)

    typedef struct node_type 
    { 
        int data; 
        struct node_type *next; 
    }; 
    

    c)用C++编译器编译你的代码。 (感谢@JonathanLeffler)

  2. 所有这些

    if (x=='y' or x=='Y'){ 
    

    if (x=='y' || x=='Y'){ 
    

    ,或者你可以只包括<iso646.h>,其中包括#define or ||在它(感谢@JonathanLeffler)来代替,

    或者你应该用C++编译器编译你的代码。

+1

或者代码应该包含''以便处理'或'等等(定义:'#define或||'或等价物)。 –

0

的添加到@leeduhem

typedef struct node_type 
{ 
    int data; 
    struct node_type *next; 
} node; 

这将导致的

typedef struct node_type node;