1
我的任務是在C++中創建鏈接列表。我應該爲LinkedList和Node創建一個結構體。在這個程序中我應該有很多函數,但是爲了我自己的理解,我現在只是想寫一個append函數。使用節點創建LinkedList 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;
}
的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個新的節點,並打印出它們的值(以確保它的工作)。
在hw10.cpp中使用第10行的頭的錯誤點,但頭在第9行而不是10,並且它看起來沒問題。這看起來不像編譯的確切源代碼,是嗎? –
@koodawg這是我寫的源代碼。 – user2821771
我編譯你的代碼並得到一個完全不同的錯誤,請參閱下面的答案。 –