前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >顺序表C语言实现

顺序表C语言实现

作者头像
发布2024-04-30 21:18:51
830
发布2024-04-30 21:18:51
举报
文章被收录于专栏:转自CSDN转自CSDN

 这是SL.h头文件

代码语言:javascript
复制
#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文件

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-04-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
腾讯云服务器利旧
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档