链表 - 约瑟夫问题

就是简单的链表操作,下面是实例。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
int tot;
struct node {
    int num;
    node() {
        num = ++tot;
    }
    node *next,*past;
};
int main() {
    int m,n;
    while(1) {
        scanf("%d%d",&n,&m);
        tot = 0;
        node *head = new node,*temp = head;
        node *tmp = head;
        for(int i = 1; i<n; i++) {
            temp -> next = new node;
            temp -> next -> past = temp;
            temp = temp -> next;
        }
        head -> past = temp;
        temp -> next = head;
        if(!m && !n) {
            break;
        }
        int to = 0;
        while(tmp -> next != tmp) {
            to ++;
            if(!(to % m)) {
                node *t = tmp;
                tmp -> past -> next = tmp -> next;
                tmp -> next -> past = tmp -> past;
                tmp = tmp -> next;
                delete t;
            } else {
                tmp = tmp -> next;
            }
        }
        printf("%d\n",tmp -> num);
        delete tmp;
    }
    return 0;
}
posted @ 2018-01-20 15:21  WenOI  阅读(106)  评论(0编辑  收藏  举报
水波背景