约瑟夫环问题(链表)

在这里插入图片描述

`#include <stdio.h>
#include <stdlib.h>

#define _DEBUG
#undef PDEBUG
#ifdef _DEBUG
    #define PDEBUG(fmt, args...) printf(fmt, ##args)
#else
    #define PDEBUG(fmt, args...)
#endif

/* 链表节点类型 */
typedef struct node{
    int val;
    struct node *next;
}ListNode;

/* 创建链表节点 */
ListNode *creatnode(int num)
{
    ListNode *p = (ListNode *)malloc(sizeof(ListNode));
    
    p->val = num;
    p->next = NULL;
    
    return p;
}

/* 创建循环链表 */
ListNode *creatJoseflist(int num)
{
    ListNode *head, *p, *tail;
    int i;
    
    for(i=0; i<num; i++)
    {
        p = creatnode(i);
        if(0 == i)
            head = p;
        else
            tail->next = p;
        tail = p;    
    }
    tail->next = head;
    return head;
}
/* 约瑟夫环问题 */
void runjoseflist( int n, int m )
{
    ListNode *head = creatJoseflist(n);
    ListNode *tail;
    int i;

    PDEBUG("delete:");
    while( head->next != head )
    {
        for(i=0; i<m-1; i++)
        {
            head = head->next;
        }
        tail = head->next;
        head->next = tail->next;
        head = head->next;
        PDEBUG("%d--", tail->val);
        //free(tail);
    }
    PDEBUG("\nthe last left:");
    PDEBUG("%d\n", head->val);
}

int main(void)
{
    int num = 8;
    int m = 2;
    
    runjoseflist(num, m);
    
    return 0;
}
发布了18 篇原创文章 · 获赞 2 · 访问量 632

猜你喜欢

转载自blog.csdn.net/weixin_39618542/article/details/102085185
今日推荐