约瑟夫环链表实现

写的蛮繁琐的,而且中间还出现了些问题

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

LinkList init(int n,LinkList R)
{
    ListNode *p,*q;
    int i;
    R=q=new ListNode;
    for(int i=1;i<n;i++)
    {
        p=new ListNode;
           q->data=i;
           q->next=p;
           q=q->next;
    }
    q->data=n;
    q->next=R;
    return R;
}

LinkList DeleteDeath(int n,int k,LinkList R)
{
     ListNode *q,*p;
     p=R;
     if(k==1)
     {
        for(int i=1;i<=n;i++)
        {
            cout<<p->data<<" ";
            p=p->next;
        }
     }
     else
     for(int i=1;i<=n;i++)
     {
         for(int j=1;j<k-1;j++)
             p=p->next;
         q=p->next;
         p->next=q->next;
         cout<<q->data<<" ";
         p=p->next;
     }
     cout<<endl;
     return R;
}
int main()
{
    LinkList R,t;
    int n,m;
    //总人数n 报数上线 m
    cin>>n>>m;
    R=init(n,R);
    DeleteDeath(n,m,R);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/curiosity9/article/details/83178462