约瑟夫问题循环链表解法、队列解法

(1)单链表解法:

typedef struct node{    //定义单链表结构,next指向下一个节点
    int key;
    node *next;
}node,*pnode;

void test(){
    int n,m;
    cout<<"number of people per circle n = ";   cin>>n;
    cout<<"the m'th person to be killed m = ";  cin>>m;
    cout<<"the kill list is: ";
    pnode ptr = (pnode)malloc(sizeof(node)*n);  //分配内存
    pnode p = ptr;  //p为头指针head
    for(int i = 0; i < n-1; i++){   //对指针赋值
        ptr->key = i+1;
        ptr->next = ptr+1;
        ptr = ptr->next;
    }
    ptr->key = n;   //最后一个指针赋值为n
    ptr->next = p;  //最后一个指针指向head p
    while(p != p->next){    //当循环链表不为空,即next不指向自身
        for(int i = 0; i < m-2; i++)    //数到第m-1个人
            p = p->next;
        cout<<p->next->key<<" ";    //输出第m个人
        p->next = p->next->next;    //将第m-1的next指向第m+1个人,即删除第m个人
        p = p->next;    //p从下一个人重新计数
    }
    cout<<p->key<<endl;
}

(2)队列解法(利用FIFO特性)

void test2(){
    queue<int> circle;  //FIFO
    int n = 12, m = 7;
    for(int i = 0; i < n; i++)
        circle.push(i+1);
    while(circle.size() != 0){
        for(int i = 0; i < m-1; i++){   //第m个人将被移除队列circle
            int temp = circle.front();
            circle.pop();
            circle.push(temp);
        }
        cout<<circle.front()<<" ";
        circle.pop();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值