我已经在这里工作了4.5个小时试图弄清楚为什么这不起作用。仍然没有运气。我不断收到分段错误,或者尽管构建成功,但列表永远不会显示。
SimpleVector.h
stop-and-wait
的main.cpp
// 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
答案 0 :(得分: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);
试试这个。它删除整个列表