
数据结构中用单向循环链表模拟约瑟夫环?
展开全部
共有三种解法:我先给你一个同密码,循环链表写的吧!
欢迎采纳并追问!
#include <stdio.h>
#include <stdlib.h>
int linktype(int n,int m) //链表结构
{
int people,passord;
struct node
{
int data;
struct node *next;
}NODE;
node *p,*head,*q,*pri;
head=(node *)malloc(sizeof(struct node));//创建一个空表
head->next=NULL;
head->data=1;
q=head;
for(int i=2;i<=n;i++)
{
p=(node *)malloc(sizeof(struct node));//让系统分配一块新的内存
p->data=i;
p->next=NULL;
q->next=p;
q=q->next;
}
q->next=head;//建立循环链表
pri=q;p=head;//从head开始循环
people=0;passord=1;//出去了几个人、记录的密码数
while(people<n)
{
pri=pri->next;
p=p->next;
passord++;
if(passord==m)
{
printf("%-4d",p->data);
node *temp;
temp=p;
pri->next=p->next;
p=p->next;
free(temp);
people++;passord=1;
}
}
printf("\n");
return 0;
}
int main()
{
int n,m;
printf("请输入人数和密码");
while(scanf("%d%d",&n,&m)!=EOF)
{
if(m<0||n<0)
{
printf("输入错误,请重新输入\n");
continue;
}
linktype(n,m);
}
system("pause");
return 0;
}
欢迎采纳并追问!
#include <stdio.h>
#include <stdlib.h>
int linktype(int n,int m) //链表结构
{
int people,passord;
struct node
{
int data;
struct node *next;
}NODE;
node *p,*head,*q,*pri;
head=(node *)malloc(sizeof(struct node));//创建一个空表
head->next=NULL;
head->data=1;
q=head;
for(int i=2;i<=n;i++)
{
p=(node *)malloc(sizeof(struct node));//让系统分配一块新的内存
p->data=i;
p->next=NULL;
q->next=p;
q=q->next;
}
q->next=head;//建立循环链表
pri=q;p=head;//从head开始循环
people=0;passord=1;//出去了几个人、记录的密码数
while(people<n)
{
pri=pri->next;
p=p->next;
passord++;
if(passord==m)
{
printf("%-4d",p->data);
node *temp;
temp=p;
pri->next=p->next;
p=p->next;
free(temp);
people++;passord=1;
}
}
printf("\n");
return 0;
}
int main()
{
int n,m;
printf("请输入人数和密码");
while(scanf("%d%d",&n,&m)!=EOF)
{
if(m<0||n<0)
{
printf("输入错误,请重新输入\n");
continue;
}
linktype(n,m);
}
system("pause");
return 0;
}
展开全部
#include <iostream.h>
#include"stdio.h"
struct node{
int data;//数据
node *next;//指向下一个结点
};
void main()
{
int m,n;
node *p=new node;
node *h=new node;
cout<<"Input M,N :"<<endl;
cin>>m>>n;
p->data=1;
p->next=p;
h=p;
if(n>1){
for(int i=2;i<=n;i++)
{
node *q=new node;
q->data=i;
p->next=q;
p=q;
}
}
else
cout<<p->data<<endl;
p->next=h;
//输出
p=h;
while(p->next!=p)
{
for(int i=1;i<m-1;i++)
p=p->next;
node *s=p->next;
p->next=p->next->next;
cout<<s->data<<" ";
p=s->next;
delete s;
}
cout<<p->data<<endl;
}
#include"stdio.h"
struct node{
int data;//数据
node *next;//指向下一个结点
};
void main()
{
int m,n;
node *p=new node;
node *h=new node;
cout<<"Input M,N :"<<endl;
cin>>m>>n;
p->data=1;
p->next=p;
h=p;
if(n>1){
for(int i=2;i<=n;i++)
{
node *q=new node;
q->data=i;
p->next=q;
p=q;
}
}
else
cout<<p->data<<endl;
p->next=h;
//输出
p=h;
while(p->next!=p)
{
for(int i=1;i<m-1;i++)
p=p->next;
node *s=p->next;
p->next=p->next->next;
cout<<s->data<<" ";
p=s->next;
delete s;
}
cout<<p->data<<endl;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询