使用 Nodes C++ 创建 LinkedList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19285628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:40:20  来源:igfitidea点击:

Creating a LinkedList with Nodes C++

c++structlinked-listheader-filesnodes

提问by user2821771

I am tasked with creating a Linked List in C++. I am supposed to create a struct for both LinkedList and Node .There are many functions I am supposed to have in this program, but for my own understanding I am justtrying to write an append function at the moment.

我的任务是在 C++ 中创建一个链表。我应该为 LinkedList 和 Node 创建一个结构体。在这个程序中我应该有很多函数,但就我自己的理解,我现在只是想写一个附加函数。

I have 3 files I'm using:

我有 3 个文件正在使用:

hw10.h

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

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;
}

To compile this code, I type in terminal:

为了编译这段代码,我在终端中输入:

g++ -o hw10 hw10.cpp main.cpp

This is the response I receive:

这是我收到的回复:

 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

My main function is supposed to create a new Linked List and append 2 new nodes, and print their values out(to assure it worked).

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

回答by Mike Makuch

Here in your struct declaration you must have append inside the struct like so;

在您的结构声明中,您必须像这样在结构内追加;

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

Try adding "-std=c++11 " to eliminate the warnings.

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