#include <iostream>
class Linklist
{
public:
//建立带头结点的空链表
Linklist()
{
head=new LinkNode;
head->next=head;
}
//复制构造函数
/*Linklist(Linklist &L)
{
head=new LinkNode;
LinkNode* p=L.head->next;
LinkNode* q=L.head;
LinkNode *s;
while (p!=head)
{
s=new LinkNode;
s->data=p->data;
q->next=s;
q=s;
p=p->next;
}
q->next=head;
}*/
~Linklist()
{
CircleClear();
delete p;
}
//每个结点的数据结构
struct LinkNode
{
int data;
LinkNode* next;
};
//删除循环链表
LinkNode* CircleClear()
{
LinkNode* p=new LinkNode;
while(head->next!=head)
{
p=head->next;
head->next=p->next;
delete p;
}
return p;
}
//寻找节点
LinkNode* CircleGetNum(int i)
{
if (i<0) return NULL;
if (i==0) return head;
LinkNode* p=head->next;
int j=1;
while(p!=head&&j<i)
{
p=p->next;++j;
}
return p;
}
//插入节点
void CircleInsert(int i,int data)
{
LinkNode* p=CircleGetNum(i-1);
if (p)
{
LinkNode* s=new LinkNode;
s->data=data;
s->next=p->next;
p->next=s;
}
}
//删除节点
LinkNode* CircleDelete(int i)
{
LinkNode* p=CircleGetNum(i-1);
LinkNode* s=p->next;
p->next=s->next;
delete s;
return s;
}
//打印节点数据
void GetNodedata(Linklist &L)
{
LinkNode* p=L.head;
LinkNode* current=p->next;
if (current==head)
{
std::cout<<"empty!"<<std::endl;
}
else
{
while (current!=head)
{
std::cout<<current->data;
current=current->next;
}
}
}
void Joesphus(Linklist &L,int n,int m)
{
LinkNode* p;
LinkNode* s=L.head;
for (int i=1;i<=n-1;++i)
{
for (int j = 1; j < m; j++)
{
s=s->next;//指向要删节点的前驱
if(s==head)
{
s=s->next;
}
}
p=s->next;//要删的节点
if (p==head)
{
p=head->next;
head->next=p->next;
}
else
{
s->next=p->next;
}
std::cout<<"删除的元素是:"<<p->data<<std::endl;
delete p;
}
int a=s->data;
std::cout<<"留下的数是:"<<a<<std::endl;
}
private:
LinkNode* head;
LinkNode* p;
};
int main()
{
Linklist L;
std::cout<<"Number:"<<std::endl;
int a;
int i=1;
while(std::cin>>a)
{
L.CircleInsert(i,a);
i++;
}
L.GetNodedata(L);
//L.CircleDelete(3);
//L.GetNodedata(L);
L.Joesphus(L,9,2);
}
约瑟夫环及单链表
最新推荐文章于 2022-03-03 23:01:13 发布