gpt4 book ai didi

c++ - 段错误 11 链表

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:59:00 26 4
gpt4 key购买 nike

<分区>

我的类(class)正在通过实现循环单链表来模拟 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;
}
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com