记录一下作业~

SeqLIst.h

#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define N 100
typedef int SLDataType;

typedef struct SeqList
{
	SLDataType* a;
	int size;
	int capacity;
}SL;

//接口
void SeqListInit(SL* ps);

void SeqListPrint(SL* ps);

bool SeqListCheckEmpty(SL* ps);

void SeqListPushBack(SL* ps, SLDataType x);

void SeqListPopBack(SL* ps);

void SeqListPushFront(SL* ps, SLDataType x);

void SeqListPopFront(SL* ps);

int SeqListFind(SL* ps, SLDataType x);

void SeqListInsert(SL* ps, int pos, SLDataType x);

void SeqListErase(SL* ps, int pos);

SeqList.c

#include "SeqList.h"

void SeqListInit(SL* ps)
{
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

void SeqListPrint(SL* ps)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

bool SeqListCheckEmpty(SL* ps)
{
	if (ps->size > 0)
		return true;
	else
		printf("SeqList is empty!\n");
}

void SeqListCheckCapacity(SL* ps, SLDataType x)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* temp = (SLDataType*)realloc(ps->a, newcapacity* sizeof(SLDataType));
		if (temp == NULL)
		{
			printf("realloc fail!\n");
			exit(-1);
		}
		ps->a = temp;
		ps->capacity = newcapacity;
	}
}

void SeqListPushBack(SL* ps, SLDataType x)
{
	SeqListCheckCapacity(ps, x);
	ps->a[ps->size] = x;
	ps->size++;
}

void SeqListPopBack(SL* ps)
{
	if (SeqListCheckEmpty(ps))
		ps->size--;
}

void SeqListPushFront(SL* ps, SLDataType x)
{
	SeqListCheckCapacity(ps, x);
	int end = ps->size - 1;
	while (end >= 0)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
}

void SeqListPopFront(SL* ps)
{
	if (SeqListCheckEmpty(ps))
	{
		int begin = 0;
		while (begin <= ps->size - 1)
		{
			ps->a[begin] = ps->a[begin + 1];
			begin++;
		}
		ps->size--;
	}
}

int SeqListFind(SL* ps, SLDataType x)
{
	int i = 0;
	while (i < ps->size)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
		i++;
	}
	return -1;
}

void SeqListInsert(SL* ps, int pos, SLDataType x)
{
	if (pos > ps->size || pos < 0) {
		printf("pos invalid!\n");
		return;
	}
	SeqListCheckCapacity(ps, x);
	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}

void SeqListErase(SL* ps, int pos)
{
	if (pos > ps->size -1  || pos < 0) {
		printf("pos invalid!\n");
		return;
	}
	if (SeqListCheckEmpty(ps))
	{
		int begin = pos + 1;
		while (begin < ps->size)
		{
			ps->a[begin - 1] = ps->a[begin];
			begin++;
		}
		ps->size--;
	}
}

“但行好事,莫问前程”