我的任务是在C++中创建链接列表。我应该为LinkedList和Node创建一个结构。我应该在这个程序中有很多函数,但是出于我的理解,我现在正试图编写一个append函数。

我正在使用3个文件:

hw10.h

#ifndef Structures_hw10
#define Structures_hw10

#include <iostream>

struct Node{
  int value;
  Node* next;
};

struct LinkedList{
  Node* head = NULL;
};

void append(int);

#endif

hw10.cpp
#include "hw10.h"

void LinkedList::append(int data){
  Node* cur = head;
  Node* tmp = new Node;
  tmp->value = data;
  tmp->next = NULL;
  if(cur->next == NULL) {
    head  = tmp;
  }
  else {
    while(cur->next != NULL){
      cur = cur->next;
    }
    cur->next = tmp;
  }

  // delete cur;
}

main.cpp
#include "hw10.h"

int main(){
  LinkedList LL;
  LL.append(5);
  LL.append(6);
  Node* cur = LL.head;
  while(cur->next != NULL){
    std::cout<<cur->value<<std::endl;
    cur = cur->next;
  }
  return 0;
}

要编译此代码,我输入终端:
g++ -o hw10 hw10.cpp main.cpp

这是我收到的回复:
 In file included from main.cpp:2:0:
hw10.h:13:16: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
In file included from hw10.cpp:1:0:
hw10.h:13:16: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
hw10.cpp: In function 'void append(int)':
hw10.cpp:10:15: error: 'head' was not declared in this scope

我的主要功能应该是创建一个新的链表,并追加2个新节点,并打印出它们的值(以确保其工作)。

最佳答案

在这里,在结构声明中,您必须像这样在结构内部附加;

struct LinkedList{
  Node* head = NULL;
  void append(int);
};

尝试添加“-std = c++ 11”以消除警告。

10-07 19:03
查看更多