C语言用循环单链表实现约瑟夫环

Kirima ·
更新时间:2024-09-21
· 216 次阅读

用循环单链表实现约瑟夫环(c语言),供大家参考,具体内容如下

源代码如下,采用Dev编译通过,成功运行,默认数到三出局。

主函数:

main.c文件

#include <stdio.h> #include "head.h" #include "1.h" int main() { Linklist L; int n; printf("请输入约瑟夫环中的人数:"); scanf("%d",&n); Createlist(L,n); printf("创建的约瑟夫环为:\n"); Listtrave(L,n); printf("依次出局的结果为:\n"); Solution(L,n); return 0; }

head.h文件:

#include "1.h" #include <stdio.h> #include <stdlib.h> typedef int Elemtype; typedef struct LNode{ Elemtype data; struct LNode *next; }LNode,*Linklist; void Createlist(Linklist &L,int n) { Linklist p,tail; L = (Linklist)malloc(sizeof(LNode)); L->next = L;//先使其循环 p = L; p->data = 1;//创建首节点之后就先给首节点赋值,使得后面节点赋值的操作能够循环 tail = L; for(int i = 2;i <= n;i++) { p = (Linklist)malloc(sizeof(LNode)); p->data = i; p->next = L; tail->next = p; tail = p; } printf("已生成一个长度为%d的约瑟夫环!\n",n); } void Listtrave(Linklist L,int n)//遍历函数 { Linklist p; p = L; for(int i = 1;i <= n;i++) { printf("%3d",p->data); p = p->next; } printf("\n"); } int Solution(Linklist L,int n) { Linklist p,s; p = L,s = L; int count = 1; while(L) { if(count != 3) { count++;p = p->next;//进行不等于3时的移位 } else { Linklist q; q = p;//用q保存p所指的位置,方便进行节点的删除 if(s->next->data == s->data)//当只有一个元素的时候 { printf("%3d\n",s->data); free(s); return OK; } else//当有两个及两个以上的元素的时候 { count = 1;//先将count重置为1 printf("%3d",p->data);//再打印出出局的值 while(s->next != p) { s = s->next;//将s移位到p的前驱节点处 } p = p->next;//使p指向自己的下一个节点 s->next = p;//进行删除 free(q); } } } }

1.h文件:

#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2

运行结果:



链表 C语言 约瑟夫环 循环 单链表

需要 登录 后方可回复, 如果你还没有账号请 注册新账号