C++数据结构算法 学习笔记(5) - 循环链表

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;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值