当约瑟夫环用链表实现时,约瑟夫环充分的使用了单链表的查询和删除,约瑟夫环就是一个循环链表,在一段距离内删除一个结点,直到全部删除为止。
//约瑟夫环
#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;
}

本文介绍了一种使用单链表实现约瑟夫环的方法,并通过C++代码详细展示了如何创建循环链表及按指定步长删除节点直至链表为空的过程。
576

被折叠的 条评论
为什么被折叠?



