创建包含节点的链接列表C++

Creating a LinkedList with Nodes C++

本文关键字:列表 C++ 链接 包含 节点 创建      更新时间:2023-10-16

我的任务是在C++中创建一个链表。我应该为链接列表和节点创建一个结构。在这个程序中我应该有很多功能,但为了我自己的理解,我现在只是试图编写一个附加函数。

我正在使用 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;
}

主.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"以消除警告。