C++ 从填充链表中分割错误
我已经做了4.5个小时,试图弄明白为什么这不起作用。还是不走运。我不断遇到分段错误,或者尽管构建成功,列表始终不会显示 SimpleVector.h main.cpp 您在linkList函数中做得不对。 此线头->下一个=结束 假设第一个节点包含10个,然后第二个节点包含9个新节点 现在开始->下一步=结束 表示10->9 现在新的节点端变为8 再次开始->下一步=结束 表示10->8 前9个已丢失。 . . 最后它将变成10->1 试试这个C++ 从填充链表中分割错误,c++,linked-list,segmentation-fault,C++,Linked List,Segmentation Fault,我已经做了4.5个小时,试图弄明白为什么这不起作用。还是不走运。我不断遇到分段错误,或者尽管构建成功,列表始终不会显示 SimpleVector.h main.cpp 您在linkList函数中做得不对。 此线头->下一个=结束 假设第一个节点包含10个,然后第二个节点包含9个新节点 现在开始->下一步=结束 表示10->9 现在新的节点端变为8 再次开始->下一步=结束 表示10->8 前9个已丢失。 . . 最后它将变成10->1 试试这个 void SimpleVector::linkL
void SimpleVector::linkList(int size){
Link *newLink = new Link; //create first link
head = newLink; //
head->data = size--; //Fill the front with data
head->next = NULL; //Point the front to no where
Link *temp = head;
do{
Link *end = new Link; //Create a new link
end->data = size--; //Fill with data
end->next = NULL; //Point to no where
temp->next=end;//Previous link will point to the end
temp=end; //Now this has become previous link
// head = end; //Move to the end
}while(size > 0); //Repeat until filled
}
它使用temp变量指向上一个节点,然后在上一个和新创建的end节点之间创建链接,然后temp变为end
编辑:
试试这个。它会删除整个列表,尽管生成成功-成功的生成只意味着程序中没有语法错误。它与逻辑是否正确或程序是否产生正确的结果无关。哪一行产生分段错误?析构函数是错误的,因为它使用未初始化的局部变量。你的编译器没有警告你吗?@PaulMcKenzie没有t@EggplantMachina-您声明了linkPtr,从未将其设置为任何值,然后在while循环中使用它。因此,您使用的是未初始化的指针。我之前尝试过类似的方法,但仍然没有成功。我认为这可能与displayresult有关,所以我将其更改为循环10次迭代,但仍然不显示anything@user64322我猜你没有读到我在主线程中关于析构函数问题的评论。你想删除析构函数中的整个列表吗?@user64322-你没有看到主线程中的明显错误吗析构函数?linkPtr设置为什么?是的,我知道,但我不知道他想在析构函数中做什么?他正在使用linkptr->next,而linkptr也未初始化。
// This program demonstrates the SimpleVector template.
#include <iostream>
#include "SimpleVector.h"
using namespace std;
int main(){
int SIZE = 10; // Number of elements
// Create a SimpleVector of ints.
SimpleVector intTable;
intTable.linkList(SIZE);
intTable.displayList();
return 0;
}
void SimpleVector::linkList(int size){
Link *newLink = new Link; //create first link
head = newLink; //
head->data = size--; //Fill the front with data
head->next = NULL; //Point the front to no where
Link *temp = head;
do{
Link *end = new Link; //Create a new link
end->data = size--; //Fill with data
end->next = NULL; //Point to no where
temp->next=end;//Previous link will point to the end
temp=end; //Now this has become previous link
// head = end; //Move to the end
}while(size > 0); //Repeat until filled
}
Link *linkPtr=head;
Link *nextPtr;// = linkPtr->next;
do
{
nextPtr = linkPtr->next;
cout<<linkPtr->data<<"\t";
delete linkPtr;
linkPtr = nextPtr;
}while(linkPtr!=NULL);