按书上写了个循环链表的类,析构函数不知道怎么写

blackdrong 2009-07-31 03:33:43

#pragma once

struct NodeType
{
NodeType* next;
NodeType* back;
int info;
};

class SpecializedList
{
public:
SpecializedList(void);
~SpecializedList(void);
SpecializedList(const SpecializedList& somelist);
void ResetForward();
void GetNextItem(int& item, bool finished);
void ResetBackward();
void GetPriorItem(int& item, bool finished);
void InsertFront(int item);
void InsertEnd(int item);
int InsertItem(int item,int index);
int Length();
private:
NodeType* head;
NodeType* currentNextPos;
NodeType* currentBackPos;
int length;
};


#include "SpecializedList.h"

SpecializedList::SpecializedList(void)
{
length = 0;
head = NULL;
}

SpecializedList::~SpecializedList(void)
{
if(head != NULL)
{
head = head->next;
delete head;
}
else
delete head;
}

void SpecializedList::ResetForward()
{
currentNextPos = NULL;
}

void SpecializedList::GetNextItem(int &item, bool finished)
{
if(currentNextPos == NULL)
currentNextPos = head->next;
else
currentNextPos = currentNextPos->next;
item = currentNextPos->info;
finished = (currentNextPos == head);
}

void SpecializedList::ResetBackward()
{
currentBackPos = NULL;
}

void SpecializedList::GetPriorItem(int& item, bool finished)
{
if(currentBackPos == NULL)
currentBackPos = head;
else
currentBackPos = currentBackPos->back;
item = currentBackPos->info;
finished = (currentBackPos == head);

}

void SpecializedList::InsertFront(int item)
{
NodeType* newNode = new NodeType;
newNode->info = item;
if(head == NULL)
{
newNode->back = newNode;
newNode->next = newNode;
head = newNode;
}
else
{
newNode->back = head;
newNode->next = head->next;
head->next->back = newNode;
head->next = newNode;
}
length++;
}

void SpecializedList::InsertEnd(int item)
{
InsertFront(item);
head = head->next;
}

int SpecializedList::InsertItem(int item, int index)
{
if(index >= length)
return 0;
else
{
NodeType* p = head;
for(int i=1;i<index;i++)
{
p = p->next;
}
NodeType* newNode = new NodeType;
newNode->next = p->next;
newNode->back = p;
p->next->back = newNode;
p->next = newNode;
length++;
return 1;
}
}

int SpecializedList::Length()
{
return length;
}


主要是SpecializedList的析构函数,~SpecializedList(void)是不是该这样写?如果一个指针被置位成NULL了,还需要用delete么?
...全文
157 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ztenv 版主 2009-07-31
  • 打赏
  • 举报
回复
每次删除后记得设置为NULL就好了;
cyldf 2009-07-31
  • 打赏
  • 举报
回复
你把指针置为NULL,就会出现野指针了。
先delete,再置为NULL。
stardust20 2009-07-31
  • 打赏
  • 举报
回复
SpecializedList::~SpecializedList(void)
{

NodeType *p;
while (head != NULL)
{
p=head;
head=head->next;
delete p;
}
}

64,281

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧