// 单链表的应用.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
using namespace std;
class ListNode {
public:
int data;
ListNode* next;
ListNode()
{
data = 0;
next = NULL;
}
ListNode(int d)
{
data = d;
next = NULL;
}
};
class List {
public:
ListNode* first;
List()
{
first = new ListNode();
}
void add(int a)
{
ListNode* b = new ListNode(a);
ListNode* temp = first;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = b;
}
int getLength()
{
ListNode* temp = first->next;
int length = 0;
while (temp)
{
length++;
temp = temp->next;
}
return length;
}
int getData(int index)
{
ListNode* temp = first->next;
int count = 0;
while (count != index)
{
temp = temp->next;
count++;
}
return temp->data;
}
void makeCircle(int current, int same)//将链表制成环链表
{
int count = 0;
ListNode* a;
ListNode* temp = first->next;
while (count != current)
{
count++;
temp = temp->next;
}
a = temp;
while (count != same)
{
count++;
temp = temp->next;
}
temp->next = a;
}
};
List getResult(int n, int m)
{
List check;
List result;
int temp1 = n / m;
int temp2 = n % m;
while (temp2 != 0)
{
result.add(temp1);
check.add(temp2);
int current = check.getLength();
for (int i = 0; i < current - 1; i++)
{
if (temp2 == check.getData(i))
{
int cu = current - 1;
result.makeCircle(i, cu);
return result;
}
}
n = temp2 * 10;
temp1 = n / m;
temp2 = n % m;
}
result.add(temp1);
return result;
}
void isCircle(ListNode* head)
{
bool flag = true;
if (head == NULL)
flag = false;
ListNode *p = head->next;
ListNode *q = head->next->next;
while (q != NULL&&flag)
{
if (q == p)
{
ListNode* a = head;
ListNode* b = p;
while (a != b)
{
a = a->next;
b = b->next;
}
cout << "循环部分为";
ListNode* start = a->next;//环的入口
ListNode* end1 = q;
ListNode* end = q;
while (start != end)
{
cout << start->data;
start = start->next;
}
cout << start->data << endl;
ListNode* e = head->next;
int x = 0;
while (e != end1)
{
x++;
cout << e->data;
if (x == 1)
cout << ".";
e = e->next;
}
cout << e->data<<endl;
return;
}
p = p->next;
if (q->next == NULL)
flag = false;
else
q = q->next->next;
}
if (!flag)
{
cout << "结果为有限小数,不存在无限循环部分。\n结果为:";
ListNode* temp = head->next;
int count = 0;
while (temp != NULL)
{
count++;
cout << temp->data;
temp = temp->next;
if (count == 1)
cout << ".";
if (!temp)
cout << endl;
}
}
}
int main()
{
int n;
int m;
cout << "Enter N: ";
cin >> n;
cout << "Enter M: ";
cin >> m;
List result = getResult(n, m);
isCircle(result.first);
}