约瑟夫问题 双链表实现

<span style="color:#cc33cc;">
/*********************************
     author   : Grant Yuan
     algorithm; 双链表、
	 time    ;2014/10/3 20:38
 *********************************/   
#include<iostream>
#include <cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;

typedef struct node
{
	int id;
	struct node *front,*next;
}Node,*PNode;
int m,n;

PNode Create_list()
{
	PNode head,p,q;
	head=(Node *)malloc(sizeof(Node));
	head->id=1;
	p=(Node *)malloc(sizeof(Node));
	p=head;
	for(int i=2;i<=n;i++)
	{
		q=(Node *)malloc(sizeof(Node));
		q->id=i;
		q->front=p;
		p->next=q;
		p=q;
	}
	p->next=head;head->front=p;
	return head;
}

void Delete_List(PNode p)
{
	while(p->next){
		PNode q;
		q=p->next;
		free(p);
		p=q;
	}
}
PNode Get_Next_Node(PNode head,int k)
{
	PNode p=head;
	for(int i=1;i<k;i++)
	{
	  p=p->next;
	}
	return p;
}
PNode Get_front_Node(PNode head,int k)
{
	PNode p=head;
	for(int i=1;i<k;i++)
	{
		p=p->front;
	}
	return p;
}

void Delete_Node(PNode p)
{
	PNode q;
	(p->front)->next=p->next;
	(p->next)->front=p->front;
}

void Print_List(PNode head)
{
	PNode p=head;
	printf("%d ",p->id);
	p=p->next;
	while(1){
	   if(p==head) break;
	   printf("%d ",p->id);
	   p=p->next;
	}
	printf("\n");
}
int main()
{
    cin>>n>>m;
    PNode head,p,q;
    head=Create_list();
	int ans;p=head;
     while(1){
		p=Get_Next_Node(p,m);
		q=p->next;ans=p->id;
	    if(p->next==p) break;
	    Delete_Node(p);
	    p=q;
     }
     printf("%d\n",ans);
    return 0;
}
</span>


转载于:https://www.cnblogs.com/codeyuan/p/4254423.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值