c语言单链表实现约瑟夫环

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

typedef struct Node
{
    int data;
    struct Node *next;
}Node_t;

Node_t *create();
int insert_tail(Node_t *head,int x);
int delete_node(Node_t *head);
void node_show(Node_t *head);
int is_empty(Node_t *head);
void realize_jo(Node_t *head,int k,int m);

int main(int argc, char const *argv[])
{
    int n = 8,k = 3,m = 4;
    int i = 0;

    Node_t *p = NULL;
    Node_t *head = create();
    if(head == NULL)
        return -1;
    for(i = 2;i < 9;i++)
    {
        insert_tail(head,i);
    } 
    node_show(head);
    realize_jo(head,k,m);

    return 0;
}


Node_t *create()
{   
    Node_t *head = malloc(sizeof(Node_t));
    if(head == NULL)
        return NULL;
    head->data = 1;
    head->next = head;

    return head;
}

int insert_tail(Node_t *head,int x)
{
    Node_t *p = head;
    Node_t *new = (Node_t*)malloc(sizeof(Node_t));
    if(new == NULL)
        return -1;
    while(p->next != head)
    {
        p = p->next;
    }

    new->data = x;
    new->next = head;
    p->next = new;
    return 0;
}

int delete_node(Node_t *head)
{
    Node_t *p = head->next;
    
    head->next = p->next;
    printf("del = %d\n",p->data);
    free(p);
    p = NULL;
    return 0;
}

void node_show(Node_t *head)
{
    Node_t *p = head->next;
    printf("data = %d\n",head->data);
    while(p != head)
    {
        printf("data = %d\n",p->data);
        p = p->next;
    }
    printf("----------------end-------------------\n");
}

int is_empty(Node_t *head)
{
    return head->next == head ? 1:0;
}

void realize_jo(Node_t *head,int k,int m)
{
    int i = 1;
    Node_t *p = head; 
    while(i++ < k-1)
    {
        p = p->next;
    }

    while(p->next != p)
    {
        
        i = 1;
        while(i++ < m)
        {
            p = p->next;
        }
        delete_node(p);
    }
    printf("last = %d\n",p->data);

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值