约瑟夫问题:
#include<stdio.h> #include<stdlib.h> #define OK 1 #define ERROR 0 #define OVERFLOW -2 typedef int status; typedef int ElemType; typedef struct CList{ ElemType location; ElemType code; struct CList *next; }CList,*ListPtr; status InitList(ListPtr *CL); status ReadList(ListPtr CL); status Joseph(ListPtr CL); void main(){ ListPtr L=NULL; int cmd=0; printf("******************************************************************\n"); printf("* InitList--1 ReadList--2 Joseph--3 Exit--0 *\n"); printf("* Enter a operation code : 1, 2, 3, 0 *\n"); printf("******************************************************************\n"); printf("\n------------------------------------------------------------------\n"); printf("\nOperation:"); scanf("%d",&cmd); while(cmd!=0){ switch(cmd){ case 1: InitList(&L); break; case 2: ReadList(L); break; case 3: Joseph(L); break; } printf("\n\n------------------------------------------------------------------\n\n"); printf("Operation:"); scanf("%d",&cmd); } } status InitList(ListPtr *CL){ int count=0; int size=0; int cd=0; ListPtr p=NULL; ListPtr q=NULL; ListPtr r=NULL; printf("\nPlease enter the total numbers of people(1--32767):"); scanf("%d",&size); if(size<1||size>32767){ printf("Please check number(1--32767).\n"); return ERROR; } else { q=malloc(sizeof(CList)); if(!q) exit(OVERFLOW); count=1; p=q; p->location=count; do{ printf("\nPlease enter NO.%d person's code:",count); scanf("%d",&cd); if(cd<1||cd>32767) printf("\nIncorrect data,Try again.\n"); }while(cd<1||cd>32767); p->code=cd; while(size>1) { r=malloc(sizeof(CList)); if(!r) exit(OVERFLOW); r->location=++count; do{ printf("\nPlease enter NO.%d person's code:",count); scanf("%d",&cd); if(cd<1||cd>32767) printf("Incorrect data,try again.\n"); }while(cd<1||cd>32767); r->code=cd; q->next=r; q=r; size--; } *CL=q; q->next=p; return OK; } } status ReadList(ListPtr CL){ int count=0; ListPtr p=NULL; if(!CL) return ERROR; else{ p=CL->next; printf("\n[People:"); printf("%d",p->location); printf("Code:%d]",p->code); p=p->next; while(p!=CL->next){ count++; if(count%3==0) printf("\n"); else printf("\t"); printf("[People:"); printf("%d",p->location); printf("Code:%d]",p->code); p=p->next; } return OK; } } status Joseph(ListPtr CL){ int n=0; int BeginNum=0; ListPtr p=NULL; ListPtr q=NULL; if(!CL) return ERROR; else { do{ printf("\nPlease enter the begin number(1--32767):"); scanf("%d",&BeginNum); if(BeginNum<1||BeginNum>32767) printf("\nIncorrect data,Try again.\n"); }while(BeginNum<1||BeginNum>32767); p=CL; printf("\n-----------------The Output List is:-----------------------\n"); while(p!=p->next){ for(n=1;n<=BeginNum-1;n++) p=p->next; q=p->next; printf("%d ",q->location); BeginNum=q->code; p->next=q->next; free(q); } printf("%d ",p->location); return OK; } }