我的任务是在C ++中创建一个链接列表。我应该为LinkedList和Node创建一个结构。我应该在这个程序中有很多函数,但是为了我自己的理解,我正在尝试编写一个追加函数。
我正在使用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个新节点,并打印出它们的值(以确保它有效)。
答案 0 :(得分:2)
在结构声明中,你必须在结构中附加,如此;
struct LinkedList{
Node* head = NULL;
void append(int);
};
尝试添加“-std = c ++ 11”以消除警告。