33,008
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
typedef struct stNode
{
int color;
int idx;
stNode* next;
}NODE, *PLIST;
const int ColorNum = 10;
PLIST createlist(int n)
{
PLIST head = NULL;
PLIST currentnode = NULL;
for (int i = 0; i < n; ++i)
{
if (NULL == currentnode)
{
head = new stNode;
head->color = rand() % ColorNum;
head->idx = i;
currentnode = head;
}
else
{
currentnode->next = new stNode;
currentnode = currentnode->next;
currentnode->color = rand() % ColorNum;
currentnode->idx = i;
}
}
currentnode->next = head;
return head;
}
bool findXXX(PLIST head, PLIST* front, PLIST* end)
{
PLIST p1;
PLIST p2;
int colors[ColorNum] = {0};
int CurColorNum;
size_t MinLenth = -1;
p1 = *front = head;
p2 = *end = head->next;
colors[p1->color] += 1;
colors[p2->color] += 1;
if (p1->color == p2->color)
{
CurColorNum = 1;
}
else
{
CurColorNum = 2;
}
int curLenth = 2;
do
{
while (CurColorNum < ColorNum)
{
p2 = p2->next;
if (colors[p2->color] == 0)
{
++CurColorNum;
}
++colors[p2->color];
++curLenth;
if (p2 == p1)
{
return false;
}
}
while (colors[p1->color] - 1 > 0)
{
--colors[p1->color];
p1 = p1->next;
--curLenth;
if (p1 == head)
{
if (MinLenth == -1)
{
return false;
}
else
{
return true;
}
}
}
if (curLenth < MinLenth)
{
*front = p1;
*end = p2;
MinLenth = curLenth;
}
--curLenth;
--CurColorNum;
--colors[p1->color];
p1 = p1->next;
} while (p1 != head);
return true;
}
void printlist(PLIST head)
{
PLIST p = head;
int i = 0;
do
{
cout << p->color << ", ";
if (++i % 10 == 0)
{
cout << endl;
}
p = p->next;
} while (p != head);
}
void printlist(PLIST front, PLIST end)
{
int nlenth = 0;
while (front != end)
{
cout << "idx = " << front->idx << ", color = " << front->color << endl;
++nlenth;
front = front->next;
}
cout << "idx = " << front->idx << ", color = " << front->color << endl;
++nlenth;
cout << "总长度 = " << nlenth << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(NULL));
PLIST head = createlist(100);
printlist(head);
cout << endl << endl;
PLIST front;
PLIST end;
findXXX(head, &front, &end);
printlist(front, end);
return 0;
}