使用C++ 创建循环链表,约瑟夫环
上代码:
#include <iostream>
using namespace std;
//约瑟夫环问题
typedef int DataType;
typedef struct Node{
DataType data;
struct Node *next;
}Node;
Node *CreateList(DataType a[], int n)
{
Node *first = new Node();
first->next = NULL;
Node *r = NULL;
Node *p = NULL;
r = first;
for(int i = 0; i < n; i++){
p = new Node();
p->data = a[i];
p->next = NULL;
r->next = p;
r = p;
}
p->next = first->next; //链表末端指向链表头
return first;
}
void DeleteData(Node *first, int x)
{
Node *p = first->next;
Node *r;
int cnt = 1; //统计节点数
while(p->next != first->next && cnt < (x -1)){
p = p->next;
cnt++;
}
r = p->next;
p->next = r->next;
delete r;
}
void PrintList(Node *first)
{
int flag = 0;
Node *p = first->next;
while(p != first->next || !flag){
cout << p->data << " ";
p = p->next;
flag = 1;
}
}
int main()
{
Node *first = NULL;
DataType Data[100];
for(int i = 1; i <= 100; i++)
Data[i - 1] = i;
first = CreateList(Data, 100);
PrintList(first);
cout << endl;
DeleteData(first, 19);
cout << "删除后:" << endl;
PrintList(first);
return 0;
}