我的班级通过实现圆形单链接列表来对约瑟夫斯问题进行模拟。我的代码编译,但是当它运行时,我会得到一个分段错误:构建列表后的11。到目前为止,我的调试使我意识到,当程序进入主函数循环的最后一个循环时,发生错误。我认为这与我首先使用的方式有关,但我不确定。任何帮助都很棒,谢谢。我正在用C 编码,如果不是很明显。
#include <iostream>
#include <string>
using namespace std;
/*
* Node structure used by the linked list.
*/
struct Node {
// The name stored in this node.
string name;
// A pointer to the next node in the list.
Node * next;
};
/*
* Build the linked list
*/
class LinkedList {
private:
//pointer to the head of the list
Node *head;
public:
// constructor for LinkedList
LinkedList(){
head = NULL;
}
/*
* Add the given value to the list, making it the head.
*/
void insert(string name){
// Remember where old head was
Node *oldHead = head;
// allocate a new node in memory
head = new Node;
// set new node's fields
head->name = name;
head->next = oldHead;
}
/*
* Remove the item on the top of the stack, returning nothing.
*/
void remove() {
// Remember what the new head will be
Node* newSecond = head->next->next;
// Deallocate the head from memory
delete head->next;
// Set the head to the new head
head->next = newSecond;
}
/*
* Shifts the head forward one node.
*/
void cycle(){
head = head->next;
}
Node* getHead(){
return head;
}
// This is the opposite of a constructor - a destructor! You (almost)
// never need these in Java, but in C++ they are essential because
// you have to clean up memory by yourself. In particular, we need to
// empty out the stack.
~LinkedList() {
// While there's a head node still left, remove the head node.
while (head != NULL) {
remove();
}
}
};
int main(){
//create the circular linked list
LinkedList circle;
int people;
cin >> people;
string soldier;
Node* first = circle.getHead();
//Insert all the names
for(int i = 0; i < people; i++){
cin >> soldier;
circle.insert(soldier);
}
//begin the killing
while(first->next != NULL){
circle.cycle();
cout << " killed " << endl;
Node* temp = first->next->next;
circle.remove();
first->next = temp;
}
}
该代码中的几个问题。首先是:
Node* newSecond = head->next->next;
如果 head->next
为null,则您将获得一个空指针解除。这导致崩溃。
但是,这种特殊崩溃的实际原因是:
while(first->next != NULL)
是一个无效的指针删除。在main()
的开头,您有:
Node* first = circle.getHead();
circle
在此时为空,因此 first
被分配为null。它一直保持无效,直到您在while
语句中将其取消。因此,您会崩溃。