﻿ C++ 中循环链表和约瑟夫环 - 鸿网互联

# C++ 中循环链表和约瑟夫环

1. 初始化
2. 插入
3. 删除
4. 定位寻找

```void ListInit(Node *pNode){
int item;
Node *temp,*target;
cout<<"输入0完成初始化"<<endl;

while(1){
cin>>item;
if(!item)
return ;
pNode = new Node ;
if(!(pNode))
exit(0);//未成功申请
pNode->data = item;
pNode->next = pNode;
}
else{
//
for(target = pNode;target->next!=pNode;target = target->next)
;
temp = new Node;
if(!(temp))
exit(0);
temp->data = item;
temp->next = pNode;
target->next = temp;
}
}
}
void ListInsert(Node *pNode,int i){ //参数是首节点和插入位置
Node *temp;
Node *target;
int item;
cout<<"输入您要插入的值:"<<endl;
cin>>item;
if(i==1){
temp = new Node;
if(!temp)
exit(0);
temp->data = item;
for(target=pNode;target->next != pNode;target = target->next)
;
temp->next = pNode;
target->next = temp;
pNode = temp;
}
else{
target = pNode;
for (int j=1;j<i-1;++j)
target = target->next;
temp = new Node;
if(!temp)
exit(0);
temp->data = item;
temp->next = target->next;
target->next = temp;
}
}
void ListDelete(Node *pNode,int i){
Node *target,*temp;
if(i==1){
for(target=pNode;target->next!=pNode;target=target->next)
;
temp = pNode;//保存一下要删除的首节点 ,一会便于释放
pNode = pNode->next;
target->next = pNode;
delete temp;
}
else{
target = pNode;
for(int j=1;j<i-1;++j)
target = target->next;
temp = target->next;//要释放的node
target->next = target->next->next;
delete temp;
}
}
int ListSearch(Node *pNode,int elem){ //查询并返回结点所在的位置
Node *target;
int i=1;
for(target = pNode;target->data!=elem && target->next!= pNode;++i)
target = target->next;
if(target->next == pNode && target->data!=elem)
return 0;
else return i;
}
```

```#include<iostream>
#include<cstdio>
using namespace std;
typedef struct Node{
int data;
Node *next;
};

Node *Create(int n){
exit(0);
int item=1;
if(n){
int i=1;
Node *temp;
while(i<=n){
temp = new Node;
if(!temp)
exit(0);
temp->data = i++;
p->next = temp;
p = temp;
}
}
return p->next;
}
void Joseph(int n,int m){
//n为总人数，m为数到第m个的退出
m = n%m;

Node *start = Create(n);

if(m){//如果取余数后的m!=0，说明 m!=1
while(start->next!=start){
Node *temp = new Node;
if(!temp)
exit(0);
for(int i=0;i<m-1;i++) // m = 3%2 = 1
start = start->next;
temp = start->next;
start->next = start->next->next;
start = start->next;
cout<<temp->data<<" ";
delete temp;
}
}
else{
for(int i=0;i<n-1;i++){
Node *temp = new Node;
if(!temp)
exit(0);
cout<<start->data<<" ";
temp = start;
start = start->next;
delete temp;
}
}
cout<<endl;
cout<<"The last person is:"<<start->data<<endl;
}
int main(){
Joseph(3,1);
Joseph(3,2);
return 0;
}

```

<