我已经在这里呆了 4.5 小时,试图弄清楚为什么这不起作用。还是没有运气。我不断遇到分段错误,或者尽管构建成功,但列表永远不会显示。
SimpleVector.h
// SimpleVector class template
#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <iomanip>
using namespace std;
class SimpleVector
{
private:
struct Link{
int data;
Link *next;
};
Link *head;
public:
// Default constructor
SimpleVector()
{head = NULL;}
// Destructor declaration
~SimpleVector();
void linkList(int);
//void insertLink(T);
void displayList();
};
//Destructor for SimpleVector
SimpleVector::~SimpleVector(){
Link *linkPtr;
Link *nextPtr;
nextPtr = head;
while(linkPtr != NULL){
nextPtr = linkPtr->next;
}
delete linkPtr;
linkPtr = nextPtr;
}
//Creation of List
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
do{
Link *end = new Link; //Create a new link
end->data = size--; //Fill with data
end->next = NULL; //Point to no where
head->next = end; //Previous link will point to the end
// head = end; //Move to the end
}while(size > 0); //Repeat until filled
}
//Creation of Link and insertion
/*
template <class T>
void SimpleVector<T>::insertLink(T){
}
*/
//Function to print the entire list
void SimpleVector::displayList(){
Link *linkPtr;
linkPtr = head;
while(linkPtr != NULL){
cout<<setprecision(3)<<linkPtr->data;
linkPtr = linkPtr->next;
}
}
#endif
主.cpp
// 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;
}
你在linkList()
函数中做错了。 这条线head->next = end;
假设第一个节点包含 10 个,然后结束包含 9(新节点)
现在head->next = end
意味着10 -> 9
现在新节点end
变为 8
再次head->next = end
意味着10 -> 8
前 9 个丢失。 . . .
最后,它将变得10 -> 1
试试这个。
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。
编辑:
Link *linkPtr=head;
Link *nextPtr;// = linkPtr->next;
do
{
nextPtr = linkPtr->next;
cout<<linkPtr->data<<"t";
delete linkPtr;
linkPtr = nextPtr;
}while(linkPtr!=NULL);
试试这个。它删除整个列表