数据结构之链表

一、约瑟夫问题

1、动态链表

#include <bits/stdc++.h>
using namespace std;
struct node{
	int data;
	node* next;
};
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	node *head,*p,*now,*prev;
	//分配第一个节点,数据值为1 
	head = new node;
	head ->data=1;
	head->next=NULL;
	now = head;
	for (int i = 2;i<=n;i++){
		p=new node;
		p->data=i;
		p->next=NULL;
		now->next=p;
		now = p;
	}
	now->next=head;
	now = head,prev =head;
	while((n--)>1){
		for (int i = 1;i<m;i++){
			prev = now;
			now = now->next;
		}
		printf("%d%c",now->data,' ');
		prev->next=now->next;
		delete now;
		now = prev->next;
	}
	printf("%d",now->data);
	delete now;
	return 0;
}

2、结构体实现静态链表

#include <bits/stdc++.h>
using namespace std;
struct node{
	int prev,data,next;
}hh[100000];
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i = 1;i<=n;i++){
		hh[i].data=i;
		hh[i].next=i+1;
		hh[i].prev=i-1;
	}
	hh[1].prev=n;
	hh[n].next=1;
	int now = 1;
	while((n--)>1){
		for (int i = 1;i<m;i++){
			now = hh[now].next;
		}
		printf("%d ",hh[now].data);
		int pre = hh[now].prev,ne = hh[now].next;
		hh[pre].next=hh[now].next;
		hh[ne].prev=hh[now].prev;
		now = ne;
	}
	printf("%d",hh[now].data);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值