代码
#include <iostream>
using namespace std;
#include<time.h>
#include<stdlib.h>
//单向循环链表
class CircleLink
{
public:
CircleLink(int val=0)
{
head_ = new Node(val);
tail_ = head_;
head_->next = head_;
}
~CircleLink()
{
Node* p = head_->next;
while (p != head_)
{
head_->next = p->next;
delete p;
p = head_->next;
}
delete head_;
}
public:
//尾插法
void insertTail(int val)
{
Node* node = new Node(val);
node->next = head_;
tail_->next = node;
tail_ = node;
}
//头插法
void insertHead(int val)
{
Node* node = new Node(val);
node->next = head_->next;
head_->next = node;
if (node->next == head_)
{
tail_ = node;
}
}
//删除一个结点
void remove(int val)
{
Node* p = head_->next;
Node* q = head_;
while (p != head_)
{
if (p->data == val)
{
q->next = p->next;
delete p;
if (q->next == head_)
{
tail_ = q;
}
return;
}
else
{
p = p->next;
q = q->next;
}
}
}
//删除多个节点
void removeAll(int val)
{
Node* p = head_->next;
Node* q = head_;
while (p != head_)
{
if (p->data == val)
{
q->next = p->next;
delete p;
if (q->next == head_)
{
tail_ = q;
}
p = q->next;
}
else
{
p = p->next;
q = q->next;
}
}
return;
}
//查询
bool find(int val) const//只读不写
{
Node* p = head_->next;
while (p != head_)
{
if (p->data == val)
{
return true;
}
else
{
p = p->next;
}
}
return false;
}
//打印链表
void show() const//只读不写
{
Node* p = head_->next;
while (p != head_)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
private:
struct Node
{
Node(int val=0){
this->data = val;
this->next = nullptr;
}
int data;
Node* next;
};
Node* head_;
Node* tail_;
};
int main()
{
CircleLink link;
srand((unsigned int)time(0));
for (int i = 0; i < 10; i++)
{
link.insertTail(rand() % 100);
}
link.show();
link.insertHead(1000);
link.show();
link.insertTail(1000);
link.insertTail(1000);
link.show();
link.remove(1000);
link.show();
link.removeAll(1000);
link.show();
if (link.find(1000))
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
}
约瑟夫环问题
struct Node
{
Node(int val = 0) {
this->data = val;
this->next = nullptr;
}
int data;
Node* next;
};
//不带头结点——p->头结点,q->尾结点
void func(Node* head, int k, int m)
{
Node* q = head;
Node* p = head;
//q指向最后一个
while (q->next != head)
{
q = q->next;
}
for (int i = 0; i < k - 2; i++)//q移动到第k-1个结点
{
q = q->next;
}
p = q->next;//p移动到第k个位置
while (1)
{
for (int i = 0; i < m-1 ; i++)//p移动到第m个位置
{
q = q->next;
}
p = q->next;
cout << p->data << " ";//输出出列人数序号
if (p == q)//退出循环条件
{
return;
}
q->next = p->next;//删除p
p = q->next;//p移动到下一个位置
}
return;
}
int main()
{
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(4);
Node n5(5);
Node n6(6);
Node n7(7);
Node n8(8);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
n6.next = &n7;
n7.next = &n8;
n8.next = &n1;
func(&n1, 1, 5);
return 0;
}