您的位置:首页 > 理论基础 > 数据结构算法

计蒜客 数据结构 链表——约瑟夫环 C++

2016-08-11 17:11 375 查看
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int _data) {
data = _data;
next = NULL;
}
};
class LinkList {
private:
Node* head;
public:
LinkList() {
head = NULL;
}
void insert(Node *node, int index) {
//若是没有头结点的话建立一个头结点
if (head == NULL) {
head = node;
head->next = head;
return;
}
//若是插入的位置是0的话,头结点不是数据元素的结点(⊙o⊙)哦!!
if (index == 0) {
node->next = head->next;
head->next = node;
return;
}
Node *current_node = head->next;
int count = 0;
while (current_node != head && count < index - 1) {
current_node = current_node->next;
count++;
}
if (count == index - 1) {
node->next = current_node->next;
current_node->next = node;
}
if (node == head->next) {
head = node;
}
}
//删除函数
void output_josephus(int m){
Node* current_node = head;
//因为是循环链表,所以没有指向空的指针,而约瑟夫环的最后就是只剩一个元素
//当当前指针指向自己的时候就是只剩一个元素
while(current_node->next != current_node){
for(int i = 1; i < m; i++){
//找到目标位置的前一个
current_node = current_node->next;
}
cout<<" * "<<endl;
cout<<current_node->next->data<<" ";
Node* delete_node = current_node->next;
current_node->next = current_node->next->next;
delete delete_node;
}
cout<<" = "<<endl;
cout<<current_node->data<<endl;
delete current_node;
}

};
int main() {
//以下是链表的操作的和下一段注释是只可以存在一部分
LinkList linklist;
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
Node *node = new Node(i);
linklist.insert(node, i - 1);
}
linklist.output_josephus(m);
//接下来是删除简历的算法
//可以整段注释掉的

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 数据结构 链表