Как вставить элемент в связанный список с помощью функции?

0

Я использую следующий код, но он показывает ошибку: ожидаемый конструктор, деструктор или преобразование типов перед * токеном. Он показывает ошибку в прототипе функции и строки объявления функции.

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

node *insert(node *head);    // the compiler is showing error here

main()
{
  int dat;
  char x,ch;
  struct node_type
  {
    int data;
    node_type *next;
  };

  typedef struct node_type node;

  //   node *head;
  node *temp;

  // head= NULL;
  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);
  }

  getch();

}

node *insert(node *temp)
{
  int dat;
  char ch;
  node *new;

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

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

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

}

Какова ошибка и как ее исправить?

  • 0
    Это int main(void) , по крайней мере, пожалуйста!
  • 1
    Где определяется «узел»? Вы включили его заголовочный файл?
Показать ещё 4 комментария
Теги:
linked-list
insert

2 ответа

1
Лучший ответ

Прежде всего, вы можете перенести определение node_type из своей основной функции, над объявлением функции insert. Ошибка состоит в том, что узел неизвестен компилятору в момент, когда он его впервые видит. Так что наверху есть что-то вроде этого:

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

typedef struct node_type node;

node* insert(node *head);

Это должно позаботиться о проблеме, о которой вы просили, но есть несколько других, о которых вам нужно позаботиться:

  1. Вы не должны разыменовывать параметр при вызове insert, так как функция ожидает указатель. Так, например, вы должны иметь это вместо этого:

    if ( ch=='y' or ch=='Y')
    {
       //insert(*temp);
       insert(temp);
    }
    
  2. В insert вас есть node* именем new, но new - это фактически ключевое слово, которое на самом деле не должно использоваться для обозначения переменной. Вы можете переименовать его в другое, и это может выглядеть так:

    // new above was replaced with newNode
    node *newNode;
    
    newNode=(node *)malloc(sizeof(node));
    
    printf("enter the data: ");
    scanf(" %d ", &dat);
    newNode->data=dat;
    newNode->next=temp;
    temp=new;
    

Надеюсь, это должно привести вас к тому моменту, когда вы сможете скомпилировать и протестировать свою программу.

  • 0
    Да, я получил его. Основной причиной было использование нового в качестве имени переменной. Код сейчас работает. Я действительно ценю твою помощь.
1

для C

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

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

node *insert(node **head);

node *new_node(void){
    int dat;
    node *new=(node *)malloc(sizeof(node));

    printf("enter the data: ");
    scanf(" %d", &dat);
    new->data = dat;
    new->next = NULL;
    return new;
}

void print(node *np){
    while(np){
        printf("%d ", np->data);
        np = np->next;
    }
    printf("\n");
}

int main(){
    int dat;
    char ch;

    node *temp = NULL;

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

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

node *insert(node **temp){
    int dat;
    char ch;
    node *new = new_node();

    new->next=*temp;
    *temp=new;

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню