FIFO先进先出C++实现
数组方法实现
#include <iostream>
#include <time.h>
using namespace std;
bool isExist(int*, int);
void insertNode(int*, int);
void initOrderArray(int*, int);
#define LENGTH 300
int main()
{
int num[LENGTH] = { 0 };
int a[4] = { 0 };
int hit_num = 0;
float p;
initOrderArray(num, LENGTH);
for (int i = 0; i < LENGTH; i++)
{
if (isExist(a, num[i]))
hit_num++;
else
insertNode(a, num[i]);
}
p = hit_num / float(LENGTH);
cout << "命中率" << p << endl;
return 0;
}
void insertNode(int* a, int n)
{
int temp = n;
int temp2 = a[0];
for (int i = 0; i < 4; i++)
{
temp2 = a[i];
a[i] = temp;
temp = temp2;
}
a[0] = n;
}
bool isExist(int* a, int n)
{
for (int i = 0; i < 4; i++)
{
if (n == a[i])
return true;
}
return false;
}
void initOrderArray(int* a, int n)
{
srand((unsigned)time(NULL));
for (int i = 0; i < n; i++)
{
a[i] = rand() % 6 + 1;
}
}
单链表实现
#include <iostream>
#include <time.h>
using namespace std;
#define LENGTH 300
void initOrderArray(int*, int);
class ListNode
{
public:
ListNode(int, ListNode*);
ListNode* next;
int data;
};
ListNode* createList();
ListNode* insertNode(ListNode*, int);
bool isExist(ListNode*, int);
ListNode::ListNode(int a, ListNode* b) {
this->data = a;
this->next = b;
}
int main()
{
ListNode* headList=createList();
int num[LENGTH] = {0};
int hit_num = 0;
float p;
initOrderArray(num, LENGTH);
for (int i = 0; i < LENGTH; i++)
{
if (isExist(headList, num[i]))
hit_num++;
else
headList =insertNode(headList, num[i]);
}
p = hit_num / float(LENGTH);
cout <<"命中率"<< p << endl;
return 0;
}
ListNode* createList()
{
ListNode* n, * m, * p;
p = new ListNode(0, NULL);
m = new ListNode(0, p);
n = new ListNode(0, m);
return n;
}
ListNode* insertNode(ListNode* s,int n)
{
ListNode* m;
m = new ListNode(n, s);
s->next->next = NULL;
return m;
}
bool isExist(ListNode* s,int n)
{
ListNode* m = s;
while (m)
{
if (m->data == n)
return true;
m = m->next;
}
return false;
}
void initOrderArray(int* a, int n)
{
srand((unsigned)time(NULL));
for (int i = 0; i < n; i++)
{
a[i] = rand() % 6 + 1;
}
}