C++中链表的问题

Problems with Linked list in C++

本文关键字:问题 链表 C++      更新时间:2023-10-16

我对C++完全陌生,正为一个简单的问题伤透脑筋。我正在尝试实现一个具有三个节点的简单链表。这是我的代码:

#include<iostream>
using namespace std;
struct node(){
  int data;
  struct node* next;
};
struct node* BuildOneTwoThree() {
  struct node* head = NULL;
  struct node* second = NULL;
  struct node* third = NULL;
  head = new node;
  second = new node;
  third = new node;
  head->data = 1;
  head->next = second;
  second->data = 2;
  second->next = third;
  third->data = 3;
  third->next  = NULL;
  return head;
};

问题显然是,为什么它不编译?:(

提前感谢您的帮助!

从结构声明中删除"()"。你的编译器应该告诉你的。

更换

struct node(){
  int data;
  struct node* next;
};

带有

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

在结构声明之后的额外语法导致了错误。后者是在C++中声明structclass的正确方法。

struct的声明有一对多余的括号。当你删除它们时,这应该是可以的:

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

()应该写在函数后面,而不是结构/类名后面。