双向链表实现约瑟夫环 2016/6/12

今天实现了一个简单的双向链表,用来完成约瑟夫环:

约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。通常解决这类问题时我们把编号从0~n-1,最后[1]  结果+1即为原问题的解。


其实,vc中有封装好的CList,但是,老用人家封装好的库,挺没意思的,今天就简单的实现了一个双向链表类,说简单,是因为只实现了与解决这次问题相关的函数,其他更多的功能,等以后有时间了再来完善吧


直接上代码:

头文件:

#pragma once
//自己实现双向链表
typedef int DATA;
class Node
{
public:
Node();
DATA data;
Node*pFormer;
Node*pNext;
};






class CRecyleList
{
public:
CRecyleList();
~CRecyleList();
void AddatHead(DATA tData);
void AddatTail(DATA tData);
void Remove(Node*tNode);
void RemoveAll();
//void AddatNode(Node*pNode);
Node*GetHeader();
Node*GetTail();
void Print();
private:
Node*pHeader;
Node*pTail;
};


class KillGame
{
public:
KillGame(int nums);         //构建多少个人的杀人游戏
Node*Start(Node*tNode,int num);//从哪个节点开始 杀人, num报几个数
Node*GetHeader();
private:
CRecyleList m_List;
};



源文件:

#include
using namespace  std;


Node::Node()
{
data = 0;
pFormer = 0;
pNext = 0;
}




CRecyleList::CRecyleList()
{
pHeader = 0;
pTail = 0;
}




CRecyleList::~CRecyleList()
{
Node*p = pHeader;
while (p!=pTail)
{
Node*m = p;
p = p->pNext;
delete m;
}
delete pTail;
}


Node* CRecyleList::GetHeader()
{
return pHeader;
}


Node* CRecyleList::GetTail()
{
return pTail;
}




void CRecyleList::AddatHead(DATA tData)
{
Node*pNode = new Node;
pNode->data = tData;
    
if (pHeader != 0)
{
pNode->pNext = pHeader;
pHeader->pFormer = pNode;
pHeader = pNode;
}
else
{
pHeader = pNode;
pTail = pNode;
}

pHeader->pFormer = pTail;
pTail->pNext = pHeader;
}




void CRecyleList::AddatTail(DATA tdata)
{
Node*pNode = new Node;
pNode->data = tdata;


if (pTail!=0)
{
pNode->pFormer = pTail;
pTail->pNext = pNode;
pTail = pNode;
}
else
{
pTail = pNode;
pHeader = pNode;
}
pTail->pNext = pHeader;
pHeader->pFormer = pTail;
}




void CRecyleList::Remove(Node*pNode)
{


if (pNode == pHeader)
{
pHeader = pNode->pNext;
}
if (pNode==pTail)
{
pTail = pNode->pFormer;
}
pNode->pFormer->pNext = pNode->pNext;
pNode->pNext->pFormer = pNode->pFormer;
delete pNode;


}
void CRecyleList::Print()
{
cout << endl;
Node*pNode = pHeader;
Node*m = pHeader;
cout << pNode->data << "    ";
pNode = pNode->pNext;
while (pNode!=m)
{
cout << pNode->data << "   ";
pNode = pNode->pNext;
}
//cout << pTail->data << endl;
}


KillGame::KillGame(int num)
{
for (int i = 0; i < num;i++)
{
//m_List.AddatHead(i);
m_List.AddatTail(i);
}
//m_List.Print();
}


Node* KillGame::Start(Node*tNode, int num)
{
Node*pNode = tNode;


while (pNode!=pNode->pFormer&&pNode!=pNode->pNext)
{
for (int i = 1; i < num;i++)
{
pNode = pNode->pNext;
}
Node*temp = pNode;
pNode = pNode->pNext;
m_List.Remove(temp);
// m_List.Print();
}
return pNode;
}




Node*KillGame::GetHeader()
{
return m_List.GetHeader();
}



main函数:

KillGame game(16);
Node*pHader = game.GetHeader();
Node*pNode=game.Start(pHader, 3);
cout << pNode->data << endl;

你可能感兴趣的:(算法)