我在添加或遍历链表时遇到问题。主项目类由另一个类使用,但我可以添加正确数量的项目,但当我向列表中添加更多数据时,应用程序似乎不再有效。
我不确定具体错误在哪里。我知道当我尝试遍历列表时应用程序崩溃了。任何想法或任何改进将不胜感激。
我可以通过将 AddOccurence 方法更改为不执行 while 循环来避免崩溃。
做
void Item::AddOccurence(int Item,int placeInLine){
ItemOccurence* ocr=myHead;
if(ocr)
{
}
代替
void Item::AddOccurence(int Item,int placeInLine){
ItemOccurence* ocr=myHead;
while(ocr)
{
}
基本上击中了第一个节点,但没有更多。
我有一个包含列表的对象。这是.h文件 #包括 使用命名空间标准;
class ItemOccurence{
public:
ItemOccurence(int line,int placeInLine,ItemOccurence* link=NULL) :myLine(line),myPlaceInLine(placeInLine),myLink(link){}
int myLine;
int myPlaceInLine;
ItemOccurence* myLink;
};
class Item {
public:
Item();
Item(string Item,int line,int placeInLine);
virtual ~Item();
void deallocate(ItemOccurence* p);
void AddOccurence(int Item,int placeInLine);
string myItem;
ItemOccurence* myHead;
private:
bool isEmpty();
};
和 .cpp 文件
#include "Item.h"
#include <string>
#include<iostream>
using namespace std;
Item::Item(string Item,int line,int placeInLine):myHead(NULL){
myItem=Item;
myHead= new ItemOccurence(line,placeInLine,NULL);
}
Item::Item():myHead(NULL){
myHead=0;
}
Item::~Item() {
deallocate(myHead);
myHead=0;
}
void Item::deallocate(ItemOccurence* p){
ItemOccurence* tmp;
while(p){
tmp=p;
p=p->myLink;
delete tmp;
}
}
void Item::AddOccurence(int Item,int placeInLine){
ItemOccurence* ocr=myHead;
while(ocr)
{
cout<<"orrucence head while adding " << myHead->myLine << " " << myHead->myPlaceInLine <<"\n";
ocr=ocr->myLink;
}
myHead = new ItemOccurence(Item,placeInLine,myHead);
return;
}
bool Item::isEmpty(){
if(myHead)
return false;
else
return true;
}
编辑:我将 AddOccurence 更新为。
void Item::AddOccurence(int line,int placeInLine){
ItemOccurence* prev = myHead;
ItemOccurence* curr = myHead->myLink;
while(curr){
prev=curr;
curr=curr->myLink;
}
// insert new ItemOccurence
cout<<"adding " <<line<< " and " << placeInLine <<"\n";
prev->myLink = new ItemOccurence(line,placeInLine);
return;
}
但是我还是崩溃了。我正在尝试调试但不确定要查找什么。
很难说出您的代码试图做什么。不幸的是,残酷的事实是,它离“工作”还很远。
这里有一些提示:
- 重新考虑你的类(class)。什么是
Item
和 ItemOccurrence
?链表是一个列表。它有元素。您可能应该将其命名为 List
和 Item
。如果需要,您可以在表示 Item
的单个类中执行此操作(List
只是前面 Item
的特例)。
- 每个
Item
都需要一个string
(节点数据)和一个next
(指向下一个节点的指针)。
- 如果您使用
List
,它需要有一个指向 head
(第一个 Item
)的指针。
- 您不需要存储
placeInLine
。 placeInLine
只应在搜索插入新 Item
的位置时使用。
- 不清楚
ItemOccurrence::myLine
应该代表什么。
- 当你初始化
myHead(NULL)
时,你不需要将它设置为0
。
isEmpty()
通常不是 private
方法。
- 添加节点的算法是:
- 循环直到找到需要插入的位置。
- 看起来您需要检查两件事:“列表末尾”和“placeInLine”
- 设置
new_node->next = current->next->next
节点。
- 设置
current->next = new_node
节点。
- 注意
current->next
为 NULL
的特殊情况。
- 代替
if (x) return true; else return false;
,常见的是return x;
我是一名优秀的程序员,十分优秀!