约瑟夫环的链表实现

当约瑟夫环用链表实现时,约瑟夫环充分的使用了单链表的查询和删除,约瑟夫环就是一个循环链表,在一段距离内删除一个结点,直到全部删除为止。

//约瑟夫环
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
    int x;
    struct node *next;
}*head;
void creat(int n)
{
    struct node  *p,*t;
    int i;
    head=(struct node*)malloc(sizeof(struct node));
    head->x=1;
    head->next=NULL;
    t=head;
    for(i=1; i<n; i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        p->x=i+1;
        t->next=p;
        t=t->next;
        if(i==n-1)
        {
            p->next=head;
        }
        else
        {
            p->next=NULL;
        }
    }
}
void dele(int n)
{
    struct node *t,*p;
    int i=1;
    if(n==1)
    {
        for(i=0; i<9; i++)
        {
            t=t->next;
        }
        i=0;
    }
    p=t->next;
    while(t!=p)
    {
        if(i==n-1)
        {
            t->next=p->next;
            cout<<p->x<<" ";
            free(p);
            p=t->next;
            i=0;
        }
        else
        {
            t=t->next;
            p=p->next;
            i++;
        }
    }
    cout<<t->x<<endl;
}
int main()
{
    int i;
    struct node *t;
    creat(10);
    t=head;

    for(i=0; i<10; i++)
    {
        cout<<t->x<<"  ";
        t=t->next;
    }
    cout<<endl;
creat(10);
//指针移动7下删除一个链表
    dele(7);
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值