采用循环链表解决围圈问题

#include <stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
typedef struct node
{
    int data;
    struct node *next;
}node;

void printlist(node *head)
{
    node *p=NULL;
    node *q=NULL;
    if(NULL==head)
    {
        printf("list null\n");
        return;
    }

    q=p=head;
    while(p->next!=q)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("%d ",p->data);

    printf("\n");
}

void josephu(node *head)
{
    int k=0;
    printf("请输入从第几个开始计数:\n");
    scanf("%d",&k);
    int m=0;
    printf("请输入数到几退出:\n");
    scanf("%d",&m);
    int i=0;
    node *p=NULL;
    node *q=NULL;
    //node *r=NULL;
    //r=p=head;
    p=head;
    printf("head:%d\n",head->data);
    for(i=1;i<k;i++)
    {
        p=p->next;
    }
    printf("head+k:%d\n",p->data);
    while(p->next!=p)
    {
        for(i=1;i<m;i++)
        {
            q=p;
            p=p->next;
        }
        printf("出队列的人是%d ",p->data);
        q->next=p->next;
        free(p);
        p=q->next;
    }
    printf("最后留下的是:%d ",p->data);
    printf("\n");
}

int main()
{
    node *newnode=NULL;
    node *ptr=NULL;
    node *head=NULL;
    int n=0;
    printf("请输入链表的个数:\n");
    cin>>n;
    int i=0;
    head=(node*)malloc(sizeof(node)); //建立链表的头指针
    head->data=1;
    ptr=head;
    for(i=2;i<=n;i++)
    {
        newnode=(node *)malloc(sizeof(node));
        newnode->data=i;
        newnode->next=NULL;
        ptr->next=newnode;
        ptr=newnode;
    }

    newnode->next=head;

    printlist(head);

    josephu(head);

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值