C++数据结构算法 学习笔记(5) - 循环链表
Joseph问题
有 10 个小朋友按编号顺序 1,2,。。。,10 顺时针方向围成一圈。从 1 号开 始顺时针方向 1,2,。。。,9 报数,凡报数 9 者出列(显然,第一个出圈为 编号 9 者)。
问题: 最后一个出圈者的编号是多少?第 5 个出圈者的编号是多少?
循环链表图示:
代码实现
代码如下
#include <iostream>
#include <string>
using namespace std;
typedef struct _LinkNode
{
int data;
struct _LinkNode* next;
}LinkNode, LinkList;
bool InitList(LinkList*& L)
{
L = new LinkNode;
if (!L)return false;
L->next = L;
L->data = -1;
return true;
}
bool ListInsert_back(LinkList*& L, LinkNode* Node)
{
LinkNode* last = NULL;
if (!L || !Node) return false;
if (L == L->next) //When the first node pointer is pointing to itself, means it's a NULL List
{
Node->next = L;
L->next = Node;
}
else //A Non-NULL loop List
{
last = L->next;
while (last->next != L) last = last->next;
Node->next = L;
last->next = Node;
}
return true;
}
void LinkPrint(LinkList* L)
{
LinkList* p;
if (!L || L == L->next)
{
cout << "This List is NULL" << endl;
return;
}
p = L->next;
while (p != L)
{
cout << p->data << "\t";
p = p->next;
}
cout << endl;
}
bool Joseph(LinkList*& L, int interval)
{
LinkList* p, * q;
int i = 0, j = 0;
int times = 0, num = 0;
p = L;
if (!L || p->next == L)
{
cout << "the list is NULL" << endl;
}
if (interval < 1)
{
cout << "The interval value cannot less than 1" << endl;
return false;
}
do
{
i += interval;
//search for the i node, p will pointing to the node;
while (p->next)
{
if (p->next!=L) j++;
if (j >= i) break;
p = p->next;
}
times++;
q = p->next; //temporary save the node address to release the memory
num = q->data;
if (times == 5) cout << "The fifth delete element inside the list is" <<num<< endl;
cout << "Current: " << q->data << " Last: " << p->data << " Next: " << q->next->data << endl;
p->next = q->next;
delete q;
LinkPrint(L);
} while (L->next != L); //While List is not NULL, keep counting
cout << "The last element come out is:" << num << endl;
return true;
}
int main()
{
LinkList* L, *s;
//1.Initial the NULL List
int i = 0;
if (InitList(L))
{
cout << "Initialling a NULL looping List" << endl;
}
else
{
exit(-1);
}
//2.Creating a Loop List(End Insert Method)
cout << "Using the end insert method, inserting 10 element inside the List" << endl;
while ((++i) <= 10)
{
s = new LinkNode;
s->data = i;
s->next = NULL;
if (ListInsert_back(L, s))
{
cout << "Sucessfully Inserted" << endl;
}
else
{
cout << "Failed to insert" << endl;
}
}
cout << "The element inside the list is" << endl;
LinkPrint(L);
//3. Solve the Joseph problem
Joseph(L, 9);
system("pause");
return 0;
}