非常详细的顺序表(c)

头文件

#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#define INIT 4
typedef int DataType;

struct str
{
	DataType* a;
	int size;
	int quantity;
}s;

void Seqilstinit(struct str*);//初始化顺序表  
void Seqilstprint(struct str*);//打印顺序表
void CheckCapacity(struct str*);//增容
void Seqilstpushback(struct str*,DataType);//尾插
void Seqilstpopback(struct str*);//尾删
void Seqilstpushhead(struct str*, DataType);//头插
void Seqilstpophead(struct str*);//头删
void SeqilstFind(struct str*,DataType);//查找
void SeqilstInsert(struct str*, size_t, DataType);//在pop位置插入x
void SeqilstErase(struct str*);//删除pop位置的值
void SeqiletDestory(struct str*);//销毁

函数实现

#include"head.h"

void Seqilstinit(struct str* p)//初始化
{
	assert(p);
	DataType* ps;
	ps= (DataType*)realloc(p->a, sizeof(DataType) * INIT);//最初开辟四个空间
	if (ps != NULL)
	{
		p->a = ps;
	}
	else
	{
		perror("raelloc");
		exit(-1);
	}
	p->quantity = INIT;
	p->size = 0;
}

void Seqilstprint(struct str* p)//打印
{
	assert(p);
	int i = 0;
	for (i = 0; i < p->size; i++)
	{
		printf("%3d",p->a[i]);
	}
}

void CheckCapacity(struct str* p)//扩容
{
	assert(p);
	if (p->quantity == p->size)
	{
		DataType* ps;
		ps = (DataType*)realloc(p->a, sizeof(DataType) * 2 * (p->quantity));
		if (ps != NULL)
		{
			p->a = ps;
		}
		p->quantity *= 2;
	}
}

void Seqilstpushback(struct str* p, DataType x)//尾插
{
	assert(p);
	if (p->quantity == p->size)
	{
		CheckCapacity(p);
	}
	p->a[p->size] = x;
	p->size++;
}

void Seqilstpopback(struct str* p)//尾删
{
	p->size--;
}

void Seqilstpushhead(struct str* p,DataType x)//头插
{
	int i=0;
	CheckCapacity(p);
	for (i =p->size-1; i>=0; i--)
	{
		p->a[i+1] = p->a[i];
	}
	p->a[0] =x;
	p->size++;
}

void Seqilstpophead(struct str* p)//头删
{
	assert(p);
	int i=0;
	for (i = 0; i < p->size; i++)
	{
		p->a[i] = p->a[i + 1];
	}
	p->size--;
}

void SeqilstFind(struct str* p, DataType x)//查找
{
	assert(p);
	DataType* b= &x;
	DataType* ps=p->a ;
	int i=0,c=0;
	for (i =0; i < p->size; i++)
	{
		c=memcmp(ps,b,sizeof(DataType));
		if (c == 0)
		{
			printf("%d在顺序表的第%d位\n", x,i+1);
		}
		ps++;
	}
}

void SeqilstInsert(struct str * p, size_t pop, DataType x)//在pop位置插入x
{
	int i=0;
	CheckCapacity(p);
	for (i = p->size - 1; i >= pop-1; i--)
	{
		p->a[i + 1] = p->a[i];
	}
	p->a[pop-1] = x;
	p->size++;
}

void SeqilstErase(struct str* p,size_t pop)//删除pop位置的值
{
	int i = 0;
	for (i = pop-1; i < p->size; i++)
	{
		p->a[i] = p->a[i + 1];
	}
	p->size--;
}

void SeqiletDestory(struct str* p)//销毁
{
	free(p->a);
	p->a= NULL;
	p->quantity = 0;
	p->size = 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值