标签:key out free 变量 表示 cas cout for mes
#include <cassert>
#include <iostream>
using namespace std;
struct Object
{
int prev;
int key;
int next;
};
constexpr int SIZE = 10;
Object array[SIZE];
int freeHead = 0;
Object list;
void Init()
{
list.prev = -1;
list.next = -1;
}
int AllocateObject()
{
if(freeHead == SIZE)
return -1;
array[freeHead].prev = array[list.next].prev;
array[freeHead].next = array[list.prev].next;
array[list.next].prev = freeHead;
array[list.prev].next = freeHead;
return freeHead++;
}
void FreeObject(int pos)
{
assert(pos >= 0 && pos < freeHead);
int listTail = --freeHead;
//delete array[pos] from list
array[array[pos].prev].next = array[pos].next;
array[array[pos].next].prev = array[pos].prev;
//move array[listTail] to array[pos]
array[pos] = array[listTail];
int listTailPrev = array[listTail].prev;
int listTailNext = array[listTail].next;
array[listTailPrev].next = pos;
array[listTailNext].prev = pos;
}
void Test()
{
Init();
for(int i = 0; i != SIZE; ++i)
cout << AllocateObject() << "\t";
cout << endl; //占用0~9全部元素
cout << AllocateObject() << endl;// -1
for(int i = 0; i != SIZE/2; ++i)
FreeObject(i); //释放下标为0 1 2 3 4的5个元素
for(int i = 0; i != SIZE/2; ++i)
cout << AllocateObject() << "\t";
cout << endl; //由于链表中元素保持紧凑,所以实际空闲下来的元素下标为5 6 7 8 9
}
//运行结果为
0 1 2 3 4 5 6 7 8 9
-1
5 6 7 8 9
链表的数组实现 令链表的所有元素在数组中保持紧凑 《算法导论》10.3-4
标签:key out free 变量 表示 cas cout for mes
原文地址:https://www.cnblogs.com/meixiaogua/p/9782541.html