习题3.10 约瑟夫环 josephus问题

/* assume a header */
/* 双向循环链表 */
struct Node;
typedef struct Node * PtrToNode;
typedef PtrToNode List;
typedef PtrToNode position;

struct Node{
    PtrToNode Previous;
    PtrToNode Next;
    int Ele;
};
/* 删除双向循环链表中的元素例程 */
Position
Delete( Position p )
{
    Position tmp;
    tmp = p->next;
    p->Previous->Next = tmp;
    tmp->Previous = p->Previous;
    free( p );
    return tmp;
}
void
josephus( List L, int m, int n )
{
    int i,count = 0;
    Position p;
    p = L->Next;
    while( n > 1 )
    {
        count = m % n;
        for(i = 0; i < count; i++)
            p = p->Next;
        p = Delete( p );
        n--;
    }
    printf("%d",p->Ele);
}
View Code

L默认为双向循环链表,L为表头,Delete为删除双向链表结点的函数

整个表结构类似一个圆圈上面加一个表头

拓展:创建一个双向循环链表,以输入为0结束

struct Node{
    PtrToNode Previous;
    PtrToNode Next;
    int Ele;
};
//创建一个双向循环链表
Position
CreateDoubleList( void )
{
   PtrToNode head,last,now;
   head = last = malloc( sizeof(struct Node ) );
   now = malloc( sizeof(strut Node ) );
   scanf("%d",&now->Ele);
   while(now->Ele != 0)
   {
       last->Next = now;
       now->Previous = last;
       last = now;
       now = malloc( sizeof( struct Node ) );
       scanf("%d",&now->Ele);
   }
   last->Next = head;
   head->Previous = last;
   free(now);
   return head;
}
View Code

创建一个单链表,类似

//创建一个单向链表

struct Node{
    int data;
    PtrToNode Next;
};
Position
CreateSingleList( void )
{
    Position head,last,now;
    head = last = malloc( sizeof( struct Node ) );
    now = malloc( sizeof( struct Node ) );
    scanf("%d",&now->data);
    while(now->data != 0)
    {
        last->Next = now;
        last = now;
        now = malloc( sizeof( struct Node ) );
        scanf("%d",&now->data);
    }
    last->Next = NULL;
    free(now);
    return head;
}
View Code

 

posted @ 2015-07-09 20:58  Gabyler  阅读(180)  评论(0编辑  收藏  举报