用单循环链表实现约瑟夫问题。
约瑟夫问题是个有名的问题:N个人围成一圈,从第一个开始报数,第M个将被杀掉,最后剩下一个,其余人都将被杀掉。例如N=6,M=5,被杀掉的人的序号为5,4,6,2,3。最后剩下1号。#include <stdio.h> #include <stdlib.h> #include "declear.h" typedef struct Node { ElemType data; struct Node *next; }Node, *CycLinkList; void JOSEPHUS(int totalNum, int startNum, int interval) { int index; CycLinkList node; CycLinkList temPtr; CycLinkList temPriorPtr; /*建立一个无头结点的循环链表*/ CycLinkList L = (CycLinkList)malloc(sizeof(Node)); L->data = 1; L->next = L; temPtr = L; for (index = 2; index <= totalNum; index++) { node = (CycLinkList)malloc(sizeof(Node)); node->data = index; temPtr->next = node; node->next = L; temPtr = node; } temPtr = L; /*找到起始位置*/ for (index = 1; index < startNum; index++) { temPriorPtr = temPtr; temPtr = temPtr->next; } while (temPtr != temPtr->next) { /*从起始位置开始找到报数为interval的位置*/ for (index = 1; index < interval; index++) { temPriorPtr = temPtr; temPtr = temPtr->next; } printf("%d\n",temPtr->data); /*从循环链表中删除该点*/ temPriorPtr->next = temPtr->next; free(temPtr); /*更新起始位置*/ temPtr = temPriorPtr->next; } } int main() { JOSEPHUS(9,2,4); return 0; }
补充:Web开发 , Jsp ,