计蒜客 数据结构 链表——约瑟夫环 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++
- 计蒜客 数据结构 链表 ——应用筛选简历 C++
- (摘)面向对象c++数据结构之基本数据结构-链表-使用链表管理器(连载中)
- C++数据结构------顺序表和链表
- 数据结构 - 有两个链表,第一个升序,第二个降序,合并为一个升序链表(C++)
- 数据结构与算法之链表(四) 约瑟夫环
- [c/c++] C数据结构: 链表 Linked List
- 数据结构 链表的lua实现 仿照C++中list 实现
- 数据结构:循环单向链表——约瑟夫环
- C/C++版数据结构之链表<三>
- C/C++版数据结构之链表<二>
- C/C++版数据结构之链表<二>
- 链表的相关操作查找插入删除(c++ 数据结构)
- C++数据结构--链表
- 数据结构学习系类列十-链表集合(c++)
- 数据结构 - 反转单链表(C++)
- 《摘》面向对象c++数据结构--基本数据结构之链表-双向链表(结束)(凌风)
- 数据结构学习系列三-单向循环链表(c++实现且应用模板)
- 数据结构_链表_多项式求导_C++实现
- 面向对象c++数据结构--基本数据结构之链表(前篇)(凌风)