私はC++リンクリストクラスを書いています。挿入と印刷を実装してテストしました。ただし、削除のためにノードポインタを返すことができないようです。削除しようとすると、次のエラーが発生します。
Node.h:11: error: expected unqualified-id before "delete"
Node.h:11: error: abstract declarator `Node*' used as declaration
Node.h:11: error: expected `;' before "delete"
Node.cpp:21: error: expected unqualified-id before "delete"
Node.cpp:21: error: expected init-declarator before "delete"
Node.cpp:21: error: expected `,' or `;' before "delete"
make.exe: *** [Node.o] Error 1
Execution terminated
これが私のコードです:
Node.h
#ifndef Node_H
#define Node_H
class Node{
int data;
Node* next;
public:
Node(int data);
void insert(int d);
Node* delete(int d);
void printOut(void);
};
#endif
Node.cpp
#include <stdio.h>
#include "Node.h"
Node::Node(int d){
data = d;
next = NULL;
}
void Node::insert(int d){
Node* n = this;
Node* current = new Node(d);
while(n->next != NULL){
n = n->next;
}
n->next = current;
}
Node* Node::delete(int d){
Node* head = this;
Node* n = this;
if (n->data = null){
return n;
}
if (n->data == d){
return n->next;
}
while(n->next != NULL){
if (n->next->data == d){
n->next = n->next->next;
return head;
}
n = n->next;
}
return head;
}
void Node::printOut(void){
Node* n = this;
while(n->next != NULL){
printf("%d ->", n->data);
n = n->next;
}
printf("%d \n", n->data);
}
主要:
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include "Node.h"
using namespace std;
int main (void){
int i = 0;
Node* root = new Node(111);
Node* result;
for (i = 0; i < 9; i++){
root->insert(i);
}
root->printOut();
result = root->delete(5);
result->printOut();
printf("Hello j \n");
getchar();
delete[] root;
return 0;
}