自调整表的数组实现

数据结构与算法分析——c语言描述 练习3.15 答案

list.h

typedef int ElementType;
#define SpaceSize 100
#ifndef _Cursor_H
#define _Cursor_H

struct SelfAdjustRecord;
typedef struct SelfAdjustRecord* SelfAdjust;
typedef int PtrToNode;
typedef PtrToNode Position;



SelfAdjust creatList(int space);
Position Find(ElementType X, SelfAdjust L);
void Insert(ElementType X, SelfAdjust L);
#endif

list.c

#include"list.h"
#include<stdlib.h>
#include"fatal.h"

struct SelfAdjustRecord {
	ElementType *arr;
	int capacity;
	int rearCur;
};


SelfAdjust creatList(int space) {
	SelfAdjust s = malloc(sizeof(struct SelfAdjustRecord));
	if (s == NULL)
		Error("out of memory");
	s->arr = malloc(sizeof(ElementType)*space);
	if (s->arr == NULL)
		Error("out of memory");
	s->capacity = space;
	s->rearCur = -1;
	return s;
}

Position Find(ElementType X, SelfAdjust s) {
	Position p=-1;
	for (int i = 0; i <= s->rearCur; i++)
		if (s->arr[i] == X)
		{
			p = i;
			break;
		}

	if (p != -1) {
		ElementType temp = s->arr[p];
		for (int i = p; i >= 1; i--) {
			s->arr[i] = s->arr[i - 1];
		}
		s->arr[0] = temp;
		return 0;
	}
	else {
		return -1;
	}
	
}

void Insert(ElementType X, SelfAdjust s) {
	if (s->rearCur + 1 == s->capacity)
		Error("out of space");
	for (int i = s->rearCur + 1; i >= 1; i--) {
		s->arr[i] = s->arr[i - 1];
	}
	s->arr[0] = X;
	s->rearCur++;
}

main.c

#include"list.h"
//#include"list.c"
#include<stdio.h>

extern struct SelfAdjustRecord {
	ElementType *arr;
	int capacity;
	int rearCur;
};

int main() {
	SelfAdjust s = creatList(60);
	Insert(1, s);
	Insert(2, s);
	Insert(3, s);
	Find(1,s);
	printf("%d", s->arr[0]);
}


你可能感兴趣的:(自调整表的数组实现)