【发布时间】:2012-06-01 22:19:39
【问题描述】:
我刚刚实现了链接列表。它工作得非常好,但甚至很难我已经看到了我无法在 Node 上创建工作析构函数的符号,这就是它在代码中未实现的原因。
- 我需要在节点上实现工作析构函数
- List 的析构函数,但这个很简单,我将只使用 Node 类的析构函数(但我需要这个)。
- 使 List 对 Node 友好,这样我就不必使用 getNext(),但我想我可以 自己处理(不知道如何,但我会找出答案)。
请看代码,完全没问题,只要你复制它就行了。
#include <cstdio>
#include <cmath>
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
class Node {
public:
Node(Node* next, int wrt) {
this->next = next;
this->wrt = wrt;
}
Node(const Node& obiekt) {
this->wrt = obiekt.wrt;
this->next = obiekt.next;
}
~Node() {}
void show() {
cout << this->wrt << endl;
}
int getWrt(){
return this->wrt;
}
Node* getNext(){
return this->next;
}
void setNext(Node* node){
this->next = node;
}
private:
Node* next;
int wrt;
};
class List{
public:
List(int wrt){
this->root = new Node(NULL, wrt);
}
List(const List& obiekt){
memcpy(&this->root,&obiekt.root,sizeof(int));
Node* el = obiekt.root->getNext();
Node* curr = this->root;
Node* next;
while(el != NULL){
memcpy(&next,&el,sizeof(int));
curr->setNext(next);
curr = next;
next = curr->getNext();
el = el->getNext();
/* curr->show();
next->show();
el->show(); */
}
}
void add(int wrt){
Node* node = new Node(NULL, wrt);
Node* el = this->root;
while(el->getNext() != NULL){
//el->show();
el = el->getNext();
}
el->setNext(node);
}
void remove(int index){
Node* el = this->root;
if(index == 0){
//deleting old one
this->root = this->root->getNext();
}
else{
int i = 0;
while(el != NULL && i < index - 1){
// el->show();
el = el->getNext();
i++;
}
if(el!=NULL){
Node* toRem = el->getNext();
Node* newNext = toRem->getNext();
el->setNext(newNext);
//deleteing old one
}
}
}
void show(){
Node* el = this->root;
while(el != NULL){
el->show();
el = el->getNext();
}
}
~List(){}
private:
Node* root;
};
int main(){
List* l = new List(1); //first list
l->add(2);
l->add(3);
l->show();
cout << endl;
List* lala = new List(*l); //lala is second list created by copy cosntructor
lala->show();
cout << endl;
lala->add(4);
lala->remove(0);
lala->show();
return 0;
}
【问题讨论】:
-
你不应该是
memcpy-ingNodes,因为它们不是 POD 对象。 -
我将首先修复缩进并将变量从
n、n2、wrt、lala重命名为有意义的名称。还要去掉using namespace std;——把它放在文件的开头是不好的做法。 -
不,这不是家庭作业。我尝试刷新我的 c++。 n 已被评论,我现在将其删除。
-
你所有的对象都是动态分配的,你没有在任何地方调用
delete。你的析构函数永远不会运行... -
另一个小修复,在 C++ 中,标题是
<cstdio>和<cstring>而不是<stdio.h>和<string.h>(因为它们在 C 中被调用)。
标签: c++ linked-list destructor