--单向循环链表
-概述
单向循环链表是对单向链表的一种改进方式,本质是链表尾节点的指针域存放头节点的地址,这种首尾相连的链表叫做单向循环链表
-约瑟夫问题
设编号分别为:1,2,...,n的n个人围坐一圈。约定序号为k(1≤k≤n)的人从1开始计数,数到 m的那个人出列,他的下一位又从1开始计数,数到m的那个人又出列,依次类推,直到所有人出列为止。假设:设n=8,k=3,m=4时,出列序列为:(6,2,7,4,3,5,1,8)
-代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX 9
typedef struct node{
int num;
struct node* next;
}node_t;
void inter_list(node_t** head);
node_t* delete_list(node_t** head);
void order_list(node_t* head,int i );
void show_list(node_t* head);
int main()
{
node_t* head_t;
inter_list(&head_t);
for(int i=2;i<=MAX;i++){
order_list(head_t,i);
}
show_list(head_t);
delete_list( &head_t);
}
void inter_list(node_t** head){
node_t* p=(node_t*)malloc(sizeof(node_t));
if(p == NULL){
printf("malloc failture\n");
exit (1);
}
memset(p,0,sizeof(node_t));
p->num = 1;
p->next = p;
*head = p;
}
void order_list(node_t* head,int i ){
node_t* p=(node_t*)malloc(sizeof(node_t));
if(p == NULL){
printf("malloc failture\n");
exit (1);
}
memset(p,0,sizeof(node_t));
p->num = i;
p->next = NULL;
node_t* pre = head;
while(pre->next != head && pre->num < i){
pre=pre->next;
}
p->next = pre->next;
pre->next = p;
}
void show_list(node_t* head){
node_t* cur=head;
int i=0;
while( i<MAX){
printf("%d---->",cur->num);
cur=cur->next;
i++;
}
}
node_t* delete_list(node_t** head){
putchar('\n');
int num1;
printf("输入从第几个人数\n");
scanf("%d",&num1);
int num2;
printf("输入数到几踢人\n");
scanf("%d",&num2);
node_t* pre=*head;
int i=1;
while(i< num1){
pre=pre->next;
i++;
}
for(int j=1;j<=MAX;j++){
for (i=1;i<num2-1;i++){
pre=pre->next;
}
node_t* delete =pre->next;
pre->next = pre->next->next;
pre = delete->next;
printf("%3d",delete->num);
free(delete);
delete=NULL;
}
}
~
~