Circular list-Joseph's problem (C language)

The Joseph problem is a typical application of circular linked lists, which are described as follows:

m people form a circle, starting from any one of them, in a clockwise order
so that everyone starts counting from 1, and the people who report to n are dequeued; then make the
people after n start counting from 1 again Make the person who reported to n dequeue ... so go on,
find out the order of the column and the number of the last person left

Set m and n to specific numbers so that m = 8 and n = 3 simulate the Joseph problem.
Insert picture description here
Here is the complete code about this function

#include<stdio.h>
#include<stdlib.h>
typedef struct CLinkList
{   int data;
    struct CLinkList *next;
}node;
int main()
{   node *L,*r,*s;
    L =(node*)malloc(sizeof(node));
    r =L;
    int n = 8,i,k = 3;
    for(i = 1;i<=n;i++)    
    {   s = (node*)malloc(sizeof(node));
        s->data = i;
        r->next = s;
        r= s;
    }
    r->next =L->next;  //让最后一个结点指向第一个有数据结点
    node *p;
    p = L->next;
    delete L;   //删除第一个空的结点
    while(p->next != p) //判断条件:因为最后肯定剩下一个人,	
                                循环链表的最后一个数据的next还是他本身
    {for(i = 1;i<k-1;i++)
        {p = p->next; }  //每k个数出列一个人
       printf("%d,",p->next->data);
       p->next = p->next->next; //将该节点从链表上删除。
       p = p->next;
      }
   	printf("%d,",p->next->data);
    return 0;
    }

The following figure is the result of execution
Insert picture description here

Published 10 original articles · won 12 · visited 1860

Guess you like

Origin blog.csdn.net/qq_44236958/article/details/88984276