训练一下尾插法和循环链表的使用。
//循环链表解决约瑟夫问题 #include <stdio.h> #include <stdlib.h> typedef struct CycleLinkList { int data; struct CycleLinkList * next; }cycleLinkList; cycleLinkList * h, * r, * s; // 头指针、尾指针 int main() { int i, j; int n, num; cycleLinkList * L; printf("请输入参与约瑟夫环的总人数及淘汰者编号:"); scanf("%d %d",&n,&num); h = (cycleLinkList *)malloc(sizeof(cycleLinkList)); r = h; for(i = 0; i < n; i++) // 尾插法建立链表 { s = (cycleLinkList *)malloc(sizeof(cycleLinkList)); s -> data = i + 1; // 为参与人员编号 r -> next = s; // 中间过程分配的空间插到尾指针后面 r = s; } r -> next = NULL; L = h -> next; while(L) { printf("%d ",L -> data); L = L -> next; } r -> next = h -> next; L = h -> next; while(L -> next != L) { for(j = 1; j < num - 1; j++) { L = L -> next; } L -> next = L -> next -> next; L = L -> next; } puts("\n最终胜利者:"); printf("%d\n",L -> data); return 0; }
运行效果:
以前不会尾插法的时候,我的循环链表是这样的:
#include <stdio.h> #include <stdlib.h> typedef struct CycleLinkList { int data; struct CycleLinkList * next; }cycleLinkList; cycleLinkList * h, * r, * s; int main() { int i, j; int n, num; h = NULL; printf("请输入参与约瑟夫环的总人数及淘汰者编号:"); scanf("%d %d",&n,&num); for(i = 0; i < n; i++) { r = (cycleLinkList *)malloc(sizeof(cycleLinkList)); if(h == NULL) h = r; else s -> next = r; r -> next = NULL; r -> data = i + 1; s = r; } r = h; while(r) { printf("%d ",r -> data); r = r -> next; } putchar(‘\n‘); r = h; while(r -> next != r) { for(j = 1; j < num - 1; j++) { r = r -> next; if(r -> next == NULL) r -> next = h; } r -> next = r -> next -> next; r = r -> next; } puts("最终胜利者:"); printf("%d \n",r -> data); return 0; }
这是我用以前的方法实现的,但有很多问题因为这样的方法会找不到头结点的,因而只有一部分可以成功实现效果:
(一)
(二)
时间: 2024-10-09 04:31:28