使用双向循环链表解决约瑟夫问题

#include<iostream>
using namespace std;

class monkey {
public:
	int No;
	monkey *next, * pre;

	monkey( int info,  monkey* preValue = 0,  monkey *nextValue = 0) {
		No = info;
		pre = preValue;
		next = nextValue;
	}
	monkey() {};

};

class MyList{
//private:
public:
	monkey *head;
	monkey *setPos(const int i);

	MyList(monkey* h) {
		//monkey tmp(0);
		head = h;
		head->No = 0;
		head->next = 0;
		head->pre = 0;
	}
	//~MyList();
	//bool isEmpty();
	//void clear();
	//int length();
	bool append(int value, monkey* tmp);
	bool remove(monkey* tmp);
	int getValue(const int i);
};
//find the ith componet of the myList;
monkey* MyList::setPos(const int i) {
	int myCount = 0;
	if (i == -1) return head;
	monkey* p = head->next;
	while (p != 0 && myCount < i) {
		p = p->next;
		myCount++;
	}
	return p;
}
bool MyList::append(int value, monkey* tmp) {
	tmp = new monkey;
	tmp->No = value;
	//if this is a empty list, then add value after head;
	if (head->next == 0) {
		
		tmp->next = head;
		tmp->pre = head;
		head->next = tmp;
		head->pre = tmp;
		//cout << tmp->pre->pre->No << endl;
		//cout << "tmp=" << tmp << "  head=" << head << endl;
	}
	else {
		//if this list isn't empty, then add value between head and head->next;
		tmp->pre = head->pre;
		
		tmp->next = head;
		head->pre->next = tmp;
		head->pre = tmp;
		//cout << head->next->No << endl;
		//cout << "tmp=" << tmp << "  head=" << head << endl;
	}
	
	return 1;
}

int MyList::getValue(int i) {
	return setPos(i)->No;
}
bool MyList::remove(monkey* tmp) {
	tmp->next->pre = tmp->pre;
	tmp->pre->next = tmp->next;
	tmp->next = 0;
	tmp->pre = 0;
	free(tmp);
	return true;
}

int main() {
	int n = 0, m = 0;
	cin >> n >> m;
	monkey mhead(0);
	MyList MonkeyList(&mhead);
	monkey tmp(0);
	for (int i = 1; i < n+1; i++) {
		
		MonkeyList.append(i,&tmp);
	}
	
	int myCount = 0;
	monkey* curPoint = MonkeyList.setPos(0);
	
	while (1) {
		//if curPoint's next point is head, then there is only one point left, done
		if (curPoint->next->No == 0 && curPoint->pre->No==0) {
			cout << curPoint->No << endl;
			break;
		}
		//if the curPoint is the head, then skip to next point;
		if (curPoint->No == 0) {
			curPoint = curPoint->next;
			continue;
		}
		myCount++;
		if (myCount == m) {
			int curNo = curPoint->No;
			monkey* nextPoint = curPoint->next;
			MonkeyList.remove(curPoint);
			curPoint = nextPoint;
			myCount = 0;
		}
		else {
			curPoint = curPoint->next;
		}
	}
	return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值