我的类正在通过实现一个循环单链表来模拟Josephus问题。我的代码可以编译,但是当它运行时,我得到了一个分段错误: 11在列表被构造之后。到目前为止,我的调试使我意识到,当程序进入main函数的最后一个while循环时,就会发生错误。我认为这与我如何使用first->next有关,但我不确定。任何帮助都是很棒的,谢谢。如果这不是很明显的话,我用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;
}
}发布于 2012-10-20 11:07:43
代码中的几个问题。首先是这样的:
Node* newSecond = head->next->next;如果head->next为NULL,那么您将得到一个NULL指针引用。这会导致崩溃。
然而,这一特定崩溃的实际原因是:
while(first->next != NULL)是一个空指针引用。在main()的开头,你有:
Node* first = circle.getHead();此时circle为空,因此为first分配了NULL。它一直保持为空,直到您在while语句中取消对它的引用。这样,你就会崩溃。
https://stackoverflow.com/questions/12984860
复制相似问题