线性表的顺序结构(c语言)

昨天上完课,今天就把线性表的顺序结构这一部分的代码复现一下吧,虽然暑假打了一遍,但是今天是完整版。

#include 
#include 
#include 

#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAX_SIZE 100
typedef int ElemType;
typedef int Status;

typedef struct
{
	ElemType* elem;
	int length;
}SqList;

Status InitList(SqList* L)
{
	L->elem = malloc(sizeof(int) * MAX_SIZE);
	L->length = 0;
	return OK;
}

Status RandomList(SqList* L)
{
	printf("请输入大小\n");
	scanf("%d",& L->length);
	int i = 0;
	SqList* p = L;
	srand(time(NULL));
	for (;i <L->length;i++)
	{
		p->elem[i] = rand();
		printf("%d ", p->elem[i]);
	}
	return OK;
}

Status GetElem(SqList* L, int i, ElemType* e)
{
	if (i<0 || i>L->length)
	{
		return ERROR;
	}
	*e= L->elem[i - 1];
	printf("%d\n", *e);
	return OK;
}

Status ListInsert(SqList* L, int i, ElemType* e)
{
	if (i<1 || i>L->length+1)
	{
		return ERROR;
	}
	if (L->length == MAX_SIZE)
	{
		return OVERFLOW;
	}
	int j;
	for (j = L->length - 1;j >= i - 1;j--)
	{
		L->elem[j + 1] = L->elem[j];
	}
	L->elem[i - 1] = *e;
	L->length = L->length + 1;
	return OK;
}


Status ListDelete(SqList* L, int i)
{
	if (i<1 || i>L->length)
	{
		return ERROR;
	}
	int j;
	for (j = i;j < L->length;j++)
	{
		L->elem[j - 1] = L->elem[j];
	}
	return OK;
}


int main()
{
	int p=1;
	SqList* L=malloc(sizeof(SqList));
	while (p)
	{
		printf("请选择你需要进行的操作\n");
		printf("0.退出\n");
		printf("1.初始化\n");
		printf("2.随机化\n");
		printf("3.取值\n");
		printf("4.插入\n");
		printf("5.删除\n");
		scanf("%d", &p);
		if (p == 1)
		{
			printf("结果是%d\n",InitList(L));
		}
		else if (p == 2)
		{
			printf("结果是%d\n", RandomList(L));
		}
		else if (p == 3)
		{
			printf("请输入需要取值的序号\n");
			int choice;
			int result;
			scanf("%d", &choice);
			printf("结果是%d\n", GetElem(L, choice, &result));
		}
		else if (p == 4)
		{
			printf("请输入需要插入的地方\n");
			int choice;
			scanf("%d", &choice);
			printf("请输入需要插入的值\n");
			int result;
			scanf("%d", &result);
			printf("结果是%d\n", ListInsert(L, choice, &result));
			int i;
			for (i = 0;i <L->length;i++)
			{
				printf("%d ", L->elem[i]);
			}
			printf("\n");
		}
		else if (p == 5)
		{
			printf("请输入需要删除的序号\n");
			int choice;
			scanf("%d", &choice);
			printf("结果是%d\n", ListDelete(L, choice));
			int i;
			for (i = 0;i <L->length;i++)
			{
				printf("%d ", L->elem[i]);
			}
			printf("\n");
		}
		else
		{
			printf("输入有误\n");
		}
		fflush(stdin);
	}
	return 0;
}

你可能感兴趣的:(算法,c语言,算法,开发语言)