约瑟夫问题--双向循环链表的创建与删除

来源:互联网 发布:金庸群侠传 武功数据 编辑:程序博客网 时间:2024/05/21 17:34

算法和数据结构就是编程的一个重要部分,你若失掉了算法和数据结构,你就把一切都失掉了。

开始理解错题目,但是创建双向链表的思路可行。

#include<iostream>  #include <stdlib.h>using namespace std;//双向循环链表  typedef int datatype;//方便修改  //当然也可以写成模板来适应更多的数据类型  struct dclist{datatype data;//数据定义  struct dclist *prior;struct dclist *next;//前驱和后继指针  };class Joseph {public:int getResult(int n, int m) {dclist *L = (struct dclist*)malloc(sizeof(struct dclist));L->next = L->prior = NULL;dclist *r = L;dclist *p;for (int i = 1; i <= n; i++){p = (struct dclist*)malloc(sizeof(struct dclist));p->data = i;p->prior = r;p->next = r->next;r->next = p;r = p;}r->next = L->next;L->next->prior = r;if (m>0)do{L = L->next;} while (--m);int t = L->data;return t;}};int main(){int n, m;cin >> n >> m;Joseph tlist;int t = tlist.getResult(n, m);cout << t;}

后面的是正确答案

#include<iostream>  #include <stdlib.h>using namespace std;//双向循环链表  typedef int datatype;//方便修改  //当然也可以写成模板来适应更多的数据类型  struct dclist{datatype data;//数据定义  struct dclist *prior;struct dclist *next;//前驱和后继指针  };class Joseph {public:int getResult(int n, int m) {dclist *L = (struct dclist*)malloc(sizeof(struct dclist));L->next = L->prior = NULL;dclist *r = L;dclist *p;for (int i = 1; i <= n; i++){p = (struct dclist*)malloc(sizeof(struct dclist));p->data = i;p->prior = r;p->next = r->next;r->next = p;r = p;}r->next = L->next;L->next->prior = r;//删除操作while (L->next != L){for (int k = 1; k < m; k++) //因为要保留L,删除p结点,所以这里循环m-1次L = L->next;p = L->next;L->next = p->next;free(p);//删除p}//int t = L->data;return t;}};int main(){int n, m;cin >> n >> m;Joseph tlist;int t = tlist.getResult(n, m);cout << t;}


阅读全文
1 0
原创粉丝点击