附代码:
/****************************************************
*
* This is a Circular List class
* Created by ZhiYu.Wang
* Current time: 2014.5.17
*
*****************************************************/
#include <iostream>
#include <cstdio>
using namespace std;
class list{
private:
// the data structure of the node in list.
struct node{
node* next;
int val;
node(){
next = NULL;
val = -1;
}
~node(){
next = NULL;
val = -1;
}
};
// root node.
node* root;
public:
// construct the list.
list(){
root = NULL;
}
// dealloc the list.
~list(){
node* tp = root;
root = root -> next;
while(root != tp){
node* rt = root;
root = root -> next;
delete rt;
}
delete root;
}
// Get the number of the last people.
int getRootVal(){
return root -> val;
}
// Insert a people to the list.
void Insert(int val){
if(root == NULL){
root = new node;
root -> val = val;
root -> next = root;
return;
}
node* rt = root -> next;
root -> next = new node;
root = root -> next;
root -> val = val;
root -> next = rt;
}
// Get the amount of the list.
int getNum() const{
node* rt = root -> next;
int cnt = 1;
while(rt != root){
cnt ++;
rt = rt -> next;
}
return cnt;
}
// Delete the k-th people from the list.
bool DeleteNum(int k, int now){
if(getNum() == 1)
return false;
k -= 1;
while(k --){
root = root -> next;
}
node* rt = root -> next;
cout << "The " << now << "-th people who will out of the circle is: ";
cout << rt -> val << endl;
root -> next = root -> next -> next;
delete rt;
return true;
}
};
// to judge the error in scan process.
bool err(){
if(cin.fail()){
cin.clear();
cin.sync();
return true;
}
return false;
}
int main(){
// create a list.
list* l = new list;
int n, k;
// scan the number n.
cout << "Please input the number of the people." << endl;
while(true){
cin >> n;
if(!err()) break;
cout << "Please try again to input the number of the people." << endl;
}
// scan the number k
cout << "Please input the number of the k." << endl;
while(true){
cin >> k;
if(!err()) break;
cout << "Please try again to input the number of the k." << endl;
}
// insert element to the list l.
for(int i = 1; i <= n; ++i)
l -> Insert(i);
// circulate to delete the element int the list l.
int now = 1;
while(l -> getNum() > 1)
l -> DeleteNum(k, now++);
// print the last people's number.
cout << "The number of last people is: ";
cout << l -> getRootVal() << endl;
// dealloc the list l.
delete l;
// return success;
return 0;
}