顺序表的实现

SeqList.h文件

#pragma once
#include<stdio.h>
#include<stdlib.h>
#define INIT_CAPACITY 4
typedef int SLDataType;
#define N 10

typedef struct SeqList
{
	SLDataType* a;
	int size;	 //有效数据个数
	int capacity;//空间的容量
}SL;

void SLInit(SL* ps);
void SLDestory(SL* s);
void SLExpend(SL* s);
void Push_Back(SL* ps, SLDataType x);
void Pop_Back(SL* ps);
void SLPrint(SL* ps);
void Push_Front(SL* ps, SLDataType x);
void Pop_Front(SL* ps);

SeqList.c文件

#include"SeqList.h"

void SeqInit(SL* ps)
{
	ps->a= (SLDataType*)malloc(sizeof(SLDataType) * INIT_CAPACITY);
	if (ps->a == NULL)
	{
		perror("malloc fail");
	}
	ps->size = 0;
	ps->capacity= INIT_CAPACITY;
}

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

void SLExpend(SL* s)
{
	SLDataType* tmp = (SLDataType*)realloc(s->a, sizeof(SLDataType)*s->capacity * 2);
	if (tmp == NULL)
	{
		perror("realloc fail");
		return;
	}
	s->a = tmp;
	s->capacity *= 2;
	printf("扩容成功\n");
}

void Push_Back(SL* ps, SLDataType x)
{
	if (ps->capacity == ps->size)
	{
		SLExpend(ps);
	}
	ps->a[ps->size++] = x;
}

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

void Pop_Back(SL* ps)
{
	if (ps->size == 0)
	{
		return;
	}
	ps->size--;
}

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

void Pop_Front(SL* ps)
{
	int pos = 1;
	while (pos < ps->size)
	{
		ps->a[pos - 1] = ps->a[pos];
		pos++;
	}
	ps->size--;
}

test.c文件

#include"SeqList.h"

int main(void)
{
	SL s;
	SeqInit(&s);
	Push_Back(&s, 1);
	Push_Back(&s, 2);
	Push_Back(&s, 8);
	Push_Back(&s, 8);
	Push_Front(&s, 100);
	Push_Front(&s, 99);
	Push_Front(&s, 98);
	SLPrint(&s);
	Pop_Front(&s);
	Pop_Front(&s);
	SLPrint(&s);
	printf("%d %d", s.capacity, s.size);
	return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值