我正在编写一个 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
这是我的代码:
节点.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
节点.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;
}