顺序表C语言实现

 这是SL.h头文件

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

typedef int SeqListType;

typedef struct SeqList
{
	SeqListType* arr;
	int next;
	int capacity;
}SL;
//调试使用

void SLPrint(SL* ps);

//初始化

void SLInit(SL* ps);

//销毁

void SLDestroy(SL* ps);

//头插 & 尾插

void SLPushBack(SL* ps, SeqListType x);//尾插
void SLPushFront(SL* ps, SeqListType x);//头插

//头销 & 尾销

void SLPopBack(SL* ps);//尾
void SLPopFront(SL* ps);//头

 这是SL.c文件

#define _CRT_SECURE_NO_WARNINGS

#include "SL.h"

void SLInit(SL* ps)
{
	ps->arr = NULL;
	ps->next = ps->capacity = 0;
}

void SLDestroy(SL* ps)
{
	if (ps->arr != NULL)
	{
		free(ps->arr);
		ps->arr = NULL;
	}
	ps->next = ps->capacity = 0;
}

void NewCapacity(SL* ps)
{
	if (ps->next == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SeqListType* tmp = (SeqListType*)realloc(ps->arr, newcapacity * sizeof(SeqListType));
		if (tmp == NULL)
		{
			perror("malloc fail!");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
}

void SLPushBack(SL* ps, SeqListType x)
{
	assert(ps);
	NewCapacity(ps);
	ps->arr[ps->next++] = x;
}

void SLPushFront(SL* ps, SeqListType x)
{
	assert(ps);
	NewCapacity(ps);
	for(int i = ps->next++;i > 0;i --)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
}

void SLPrint(SL* ps)
{
	for (int i = 0; i < ps->next; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("|| \n");
}

void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->next);
	ps->next--;
}

void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->next);
	for (int i = 0; i < ps->next - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->next--;
}

 这是测试main

#define _CRT_SECURE_NO_WARNINGS
#include "SL.h"

int main()
{
	SL A;
	SLInit(&A);
	SLPushBack(&A, 0);
	SLPrint(&A);
	SLPushBack(&A, 1);
	SLPrint(&A);
	SLPushFront(&A, 2);
	SLPrint(&A);
	SLPopBack(&A);
	SLPrint(&A);
	SLPushBack(&A, 5);
	SLPrint(&A);
	SLPopFront(&A);
	SLPrint(&A);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值