算法导论10-3中的结构。
//LinkByArray.h
#ifndef LINKBYARRAY_H_INCLUDED
#define LINKBYARRAY_H_INCLUDED
class LinkByMulArray{
private:
int size;//已有的元素个数
int increase;//存储空间不够时增加的空间个数
int length;//空间个数
int* prev;//存储prev
int* key;//存储值
int* next;//存储next
int head;//表头
int free;//空闲链表的表头
int allocate();//分配一个空间
void Free(int);//释放一个空间
void inflate();//增加存储空间
public:
LinkByMulArray();
int search(int);//查找元素,找不到时返回-1,找到了就返回下标
void Delete(int);//删除一个元素
void insert(int);//插入一个元素
void print();//打印链表中的值
};
#endif // LINKBYARRAY_H_INCLUDED
//LinkByArray.cpp
#include "LinkByArray.h"
#include <iostream>
#include <cstring>
using namespace std;
LinkByMulArray::LinkByMulArray():size(0),length(20),increase(10),head(-1),free(0){
prev = new int[length];
key = new int[length];
next = new int[length];
memset(key,-1,sizeof(int)*length);//数组key全部设为-1
for(int i = 0; i < length;i++){//初始化prev和next
if(i == length - 1){
next[i] = -1;
prev[i] = i - 1;
}else if(i == 0){
prev[i] = -1;
next[i] = i + 1;
}else{
next[i] = i+1;
prev[i] = i-1;
}
}
}
void LinkByMulArray::inflate(){
int newLength = length + increase;
int* newPrev = new int[newLength];
int* newKey = new int[newLength];
int* newNext = new int[newLength];
memcpy(newPrev,prev,sizeof(int)*length);//把原数组的数值全部复制到新数组中
memcpy(newKey,key,sizeof(int)*length);
memcpy(newNext,next,sizeof(int)*length);
for(int i = length; i < newLength; i++){//初始化新空间里的prev和next
if(i == newLength - 1){
newNext[i] = -1;
newPrev[i] = i - 1;
}else{
newNext[i] = i+1;
newPrev[i] = i-1;
}
}
free = length;//free指向新分配的空间
length = newLength;
delete[] prev;//释放原数组
delete[] key;
delete[] next;
prev = newPrev;
key = newKey;
next = newNext;
}
int LinkByMulArray::allocate(){
if(free == -1){
inflate();
}
int temp = free;
free = next[free];
return temp;
}
void LinkByMulArray::Free(int i){
next[i] = free;
free = i;
}
void LinkByMulArray::insert(int i){//表头插入
int index = allocate();
key[index] = i;
next[index] = head;
prev[next[index]] = index;
prev[index] = -1;
head = index;
size++;
}
int LinkByMulArray::search(int k){
int i;
for(i = head; (i != -1)&&(key[i] != k);i = next[i]);
return i;
}
void LinkByMulArray::Delete(int i){
int temp = search(i);
if(temp != -1){
prev[next[temp]] = prev[temp];
next[prev[temp]] = next[temp];
Free(temp);
if(temp == head){
head = next[temp];
}
}
size--;
}
void LinkByMulArray::print(){
for(int i = head, j = 0; (i != -1)&&(j < size); i = next[i],j++){
cout << key[i] << endl;
}
}
//main.cpp
#include <iostream>
#include "LinkByArray.h"
using namespace std;
int main()
{
LinkByMulArray l;
for(int i = 0; i < 30; i++){
l.insert(i);
}
l.Delete(23);
l.print();
return 0;
}