约瑟夫环游戏->链表和顺序表实现

版权声明:欢迎大佬批评指正!O(∩_∩)O https://blog.csdn.net/wyh1618/article/details/84563907
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
typedef struct Staff
{
    int number;
    struct Staff *next;
}LinkNode;
void DispList(LinkNode *L);
void InitList(LinkNode *&L)//初始化链表
{
    L=(LinkNode *)malloc(sizeof(LinkNode));
    L->next=NULL;
}
void CreatList(LinkNode *&L)//创建链表
{
    LinkNode *s,*r,*r1;
    L=(LinkNode *)malloc(sizeof(LinkNode));
    r=r1=L;
    r->number=1;
    for(int i=2;i<31;i++)
    {
        r=(LinkNode *)malloc(sizeof(LinkNode));
        r->number=i;
        r1->next=r;
        r1=r;
    }
    r->next=NULL;
    cout<<"总人数:"<<endl;
    DispList(L);
    cout<<endl;
    r->next=L;
    //DispList(L);
}
void DispList(LinkNode *L)//输出链表
{
    LinkNode *p=L;
    //cout<<"test"<<endl;
    while(p!=NULL)
    {
        printf("%d ",p->number);
        p=p->next;
    }
    printf("\n");
}
int ListDelete(LinkNode *&L)//删除链表中第i个位置上的元素
{
    LinkNode *p=L,*q;
    cout<<"淘汰次序:"<<endl;
    for(int i=1;i<30;i++)
    {
        for(int j=1;j<8;j++)
        {
            p=p->next;
        }
        q=p->next;
        cout<<q->number<<' ';
        p->next=q->next;
        p=q->next;
        delete(q);
    }
    cout<<endl<<endl;
    cout<<"幸存者:"<<endl;
    return p->number;
}
int main()
{
    int n,m,i,j,k;
    LinkNode *L;
    InitList(L);
    CreatList(L);
    cout<<ListDelete(L)<<endl;
    return 0;
}
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
typedef struct Staff
{
    int data[999];
    int length;
}Sqlist;
int Init(Sqlist *&L)
{
    L=(Sqlist *)malloc(sizeof(Sqlist));
    L->length=0;
}
void CreatList(Sqlist *&L)
{
    for(int i=0;i<30;i++)
    {
        L->data[i]=1;
    }
    L->length+=30;
}
void ListDelete(Sqlist *&L)
{
    int j=1,t=-1;
    for(int i=1;i<=L->length;i++)
    {
        j=1;
        while(j<=9)
        {
            t=(t+1)%30;
            if(L->data[t]==1)
            {
                j++;
            }
        }
        L->data[t]=0;
        cout<<t+1<<endl;
    }
}
int main()
{
    Sqlist *L;
    Init(L);
    CreatList(L);
    ListDelete(L);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wyh1618/article/details/84563907