顺序表的代码

顺序表的感觉和理解

通讯录便用的是顺序表的结构,顺序表是将数据依次存储,形成一条线,一般要数组存储,顺序表分为静态顺序表和动态顺序表,静态该顺序表的大小已经决定好,代码运行不可更改,而动态可以通过malloc开辟,用ralloc再次分配空间

game.h

#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef int SLDateType;
typedef struct SeqList
{
	SLDateType* a;
	int sit;
	int capacity;
}SeqList;

// 对数据的管理:增删查改 
void SeqListInit(SeqList* ps);
void SeqListDestroy(SeqList* ps);

void SeqListPrint(SeqList* ps);
void SeqListPushBack(SeqList* ps, SLDateType x);
void SeqListPushFront(SeqList* ps, SLDateType x);
void SeqListPopFront(SeqList* ps);
void SeqListPopBack(SeqList* ps);

// 顺序表查找
int SeqListFind(SeqList* ps, SLDateType x);
// 顺序表在pos位置插入x
void SeqListInsert(SeqList* ps, int pos, SLDateType x);
// 顺序表删除pos位置的值
void SeqListErase(SeqList* ps, int pos);

game.c

#include"game.h"
#define _CRT_SECURE_NO_WARNINGS 1
#define k sizeof(int *)
#include<string.h>
void SeqListInit(SeqList* ps)
{
	ps->capacity = 5;
	//最大存储量
	ps->sit = 0;
	ps->a= malloc(ps->capacity * k);
}
void SeqListDestroy(SeqList* ps)
{
	free(ps->a);
	ps->a = NULL;

}
void SeqListPrint(SeqList* ps)
{
	int num;
	for (num = 0; num < ps->sit; num++)
		printf("%d", ps->a[num]);
	printf("\n");
}
void SeqListPushBack(SeqList* ps, SLDateType x)
{
	ps->a[ps->sit++] = x;
	if (ps->sit == ps->capacity)
	{
		int* tpt = realloc(ps->a, ps->capacity * 2 * k);
		if (tpt == NULL)
		{
			perror(realloc);
			return;
		}
		ps->capacity *= 2;
		ps->a = tpt;
	}
}
void SeqListPushFront(SeqList* ps, SLDateType x)
{
	memmove(ps->a + 1, ps->a, ps->sit * 4);
	ps->sit++;
	*ps->a = x;
	if (ps->sit == ps->capacity)
	{
		int* tpt = realloc(ps->a, ps->capacity * 2 * k);
		if (tpt == NULL)
		{
			perror(realloc);
			return;
		}
		ps->capacity *= 2;
		ps->a = tpt;
	}
}
void SeqListPopFront(SeqList* ps)
{
	assert(ps->sit);
	ps->sit--;
	memmove(ps->a, ps->a + 1, ps->sit * 4*1);
}
void SeqListPopBack(SeqList* ps)
{
	assert(ps->sit);
	ps->sit--;
}
// 顺序表查找
int SeqListFind(SeqList* ps, SLDateType x)
{
	int i;
	for (i = 0; i < ps->sit; i++)
	{
		if (ps->a[i] == x)
			return i+1;
	}
}
// 顺序表在pos位置插入x
void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
	assert(pos>=1&&pos<=ps->sit);
	memmove(ps->a + pos , ps->a + pos-1, (ps->sit - pos+1) * 4);
	ps->a[pos-1] = x;
	ps->sit++;
	if (ps->sit == ps->capacity)
	{
		int* tpt = realloc(ps->a, ps->capacity * 2 * k);
		if (tpt == NULL)
		{
			perror(realloc);
			return;
		}
		ps->capacity *= 2;
		ps->a = tpt;
	}
}
// 顺序表删除pos位置的值
void SeqListErase(SeqList* ps, int pos)
{
	assert(pos>=1&&pos<=ps->sit);
	assert(ps->sit);
	if (pos > ps->sit)
		return;
	memmove(ps->a + pos-1, ps->a + pos , (ps->sit - pos ) * sizeof(int));
	ps->sit--;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值