簡體   English   中英

C中的鏈表實現

[英]linked list implementation in C

在以下用於鏈表實現的代碼中,我得到以下錯誤cannot convert node_type to node * for argument 1 to 'node *insert(node *)' 我不明白這則訊息。 基本上,程序無法從main()調用函數insert

有人可以幫忙解釋一下嗎?

#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. struct node_type的定義

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

    根據C語法是不正確的,在typedef struct node_type node;之前,類型node_type不存在typedef struct node_type node; 聲明。

    要解決此問題,您可以

    a)像這樣定義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 ++編譯器來編譯代碼。

添加到@leeduhem

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

這將使額外的行無效

typedef struct node_type node;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM