多语言展示
当前在线:653今日阅读:23今日分享:25

c语言不带头结点的循环链表joseph问题

题目描述:      原始的Joseph问题的描述如下:有n个人围坐在一个圆桌周围,把这n个人依次编号为1,…,n。从编号是start的人开始报数,数到第num个人出列,然后从出列的下一个人重新开始报数,数到第num个人又出列,…,如此反复直到所有的人全部出列为止。比如当n=6,start=1,num=5的时候,出列的顺序依次是5,4,6,2,3,1。
工具/原料

电脑一台

方法/步骤
1

以下是不带头结点的循环链表算法*/#include #include typedef int data_t;typedef struct node{ data_t data; struct node *next;}listnode, *linklist;

2

/*创建一个不带头节点的循环链表*/listnode* CreatCycleList(int num){ int i = 2; listnode *head = NULL, *q = NULL, *p = NULL; head = (listnode*)malloc(sizeof(listnode)); head->data = 1; head->next = NULL; p = head; while(i <= num) { q = (listnode*www.gzlij.com)malloc(sizeof(listnode)); q->data = i; q->next = NULL; p->next = q; p = q; i++; } p->next = head; return head;}listnode* Joseph(listnode *head, int start, int killNum){ int i; listnode *p, *q;      //p遍历链表,q指向待宰的人 p = head;

3

/* 找位置,p最后停在开始报数的前一个人处*/ if(start == 1) { while(p->next != head) { p = p->next; } } else { for(i = 1; i < start-1; i++) { p = p->next; } }

4

/* 开杀*/ while(p != p->next) { for(i = 1; i < killNum; i++) { p = p->next; } q = p->next; p->next = q->next; printf('%d,',q->data); free(q); q = NULL; } return p; }void Display(listnode *head){ listnode *p = head; while(p->next != head) { printf('%d,',p->data); p = p->next; } printf('%d\n',p->data);}int main(int argc, char *argv[]){ listnode *head = CreatCycleList(5); Display(head); listnode *p = Joseph(head, 8, 3); printf('%d\n',p->data); return 0;}

推荐信息