1. 程式人生 > >HYIT邱老師資料結構課程————環形連結串列

HYIT邱老師資料結構課程————環形連結串列

#include<iostream>
using namespace std;
struct Node {
	int number, data;
	Node *next;
};
Node *Tail(int n)//尾插法,有n個人
{
	if (n == 0)
		return NULL;
	int num;
	cin >> num;//每個人身上的數字
	Node *L = new Node;//定義一個類似於頭節點的節點目的是環形有一個插入的起點
	L->data = num;
	L->number = 1;
	L->next = L;
	for (int i = 2; i < n; i++)
	{
		Node *p = new Node;
		int num;
		cin >> num;
		p->data = num;
		p->number = i;//確定是第幾個孩子的數字
		p->next = L->next;
		L->next = p;
		L = L->next;
	}
	cout << endl;
	L = L->next;
	return L;
}
int Size(Node *&L)//連結串列結點個數
{
	if (L == NULL)
	{
		return 0;
	}
	int i = 1;//計數器
	Node *p = L->next;
	while (p != L)
	{
		i++;
		p = p->next;
	}
	return i;
}
int Visit(Node *&L)//遍歷
{
	Node *p = L;
	if (p == NULL)
	{
		cout << "人數為0" << endl;
		return 0;	
	}
	cout << endl;
	cout << p->data << " ";
	p = p->next;
	while (p != L)
	{
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
	return 1;
}
int Joseph(Node *&L, int m)//實現環形
{
	if (L == NULL)
	{
		cout << "人數為空,出列結束" << endl;
		return 0;
	}
	Node *p = L;
	while (p->next != L)
		p = p->next;
	cout << "出列編號為";
	for (int n = Size(L); n > 0; n--)
	{
		for (int i = 1; i <= m % n - 1; i = i + 5)
			p = p->next;
		cout << p->next->number << " ";
		m = p->next->data;
		Node *q = p->next;
		p->next = q->next;
		free(q);
	}
	return 1;
}
int main()
{
	int m, n;
	cout << "請輸入初始編碼(正整數)和人數" << endl;
	cin >> m >> n;
	cout << endl << "請輸入" << n << "個人的編碼" << endl;
	Node *L = Tail(n);
	cout << n << "個人的編碼為";
	Visit(L);
	cout << n << "個人的出列順序為" << endl;
	Joseph(L, m);
	return 0;
}