我的班级正在通过实施循环单链表来模拟约瑟夫斯问题。我的代码编译,但是当它运行时,我得到一个分段错误:11列表构建完成后。到目前为止,我的调试让我意识到当程序进入main函数的最后while循环时会发生错误。我认为它与我如何使用第一个>接下来有关,但我不确定。任何帮助都会很棒,谢谢。如果不明显的话,我用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;
}
}
答案 0 :(得分:0)
该代码中的几个问题。首先是:
Node* newSecond = head->next->next;
如果head->next
为NULL,那么您将获得NULL指针取消引用。这会导致崩溃。
然而,这次特殊崩溃的实际原因是:
while(first->next != NULL)
是一个NULL指针取消引用。在main()
的开头,你有:
Node* first = circle.getHead();
此时 circle
为空,因此first
被指定为NULL。并且它保持为NULL,直到您在while
语句中取消引用它。因此,你会崩溃。