顺序表C语言实现

2024-04-30 21:18:51 浏览数 (1)

 这是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;
}

0 人点赞