数据结构——顺序表以及顺序表的简单应用

首先顺序表是线性表的一种,类似于数组,记录在内存中是挨着逐一放置的。
顺序表使用方便,但如果有大量数据,进行插入和删除将非常麻烦,因为需要移动大量的数据,而且数据元素个数固定。

现在要进行一下几种操作,并在其中解释顺序表。
1.顺序表的定义
2.创建空顺序表
3.判断顺序表是不是空
4.判断顺序表是否满
5.清空顺序表
6.求表长
7.在表中指定位置插入元素
8.从顺序表中删除指定位置的元素
9.打印表中所有数据

1.顺序表的定义

#include <stdio.h>
#include <stdlib.h>//结构体的头文件(关于各种头文件的总结在我之前的博客里有总结)
typedef struct
{
	int data[100];//储存顺序表的数组
	int last;//元素个数(当表空时,last = 0, last 同时也是下一个要存储数据的位置)
}sqlist_t;//这里是结构体的类型重定义,目的是代替原始结构体冗长的名字,更简洁的调用结构体。

2.创建空顺序表

sqlist_t *CreateEmptySqlist() //空顺序表函数名
{
	sqlist_t *p = malloc(sizeof(sqlist_t));//动态内存分配给顺序表
	p->last = 0;
	return p;
}

3.判断顺序表是不是空

int EmptySqlist(sqlist_t *p)
{
	if(p->last == 0)
		return 1;//空返回1
	else
		return 0;//不空返回0
}

4.判断顺序表是不是满

int FullSqlist(sqlist_t *p)
{
	if(p->last == 100)//因为表长设定的是100
		return 1;
	else
		return 0;
}

5.清空顺序表

void ClearSqlist(sqlist_t *p)
{
	p->last = 0;//让整个顺序表为0
}

6.求出顺序表表长

int LengthSqlist(sqlist_t *p)
{
	return p->last;//返回表的最后一位,也就意味着 求出表长
}

7.在表中指定位置插入元素

int InsertSqlist(sqlist_t *p, int pos, int x)//pos 插入元素的位置;x  要插入的元素
{
	int i;
	if(pos > p->last || pos < 0)
		return -1;//错误判断
	for(i = p->last; i >= pos; i--)
	{
		p->data[i + 1] = p->data[i];
	}	
	p->data[pos] = x;
	p->last++;
	return 0;
}

8.从顺序表中删除指定位置的元素

int DeleteSqlist(sqlist_t *p, int pos)//pos 删除元素的位置
{
	int i;
	if(pos >= p->last || pos < 0)
		return -1;//错误判断
	for(i = pos; i < p->last; i++)
	{
		p->data[i] = p->data[i + 1];
	}
	p->last--;
	return 0;
}

9.打印表中所有数据

void print_all(sqlist_t *p)
{
	int i;
	for(i = 0; i < p->last; i++)//p->last为表尾
		printf("%d,", p->data[i]);
	printf("\n");
}

10.主函数

int main()
{
	sqlist_t *p = CreateEmptySqlist();
	InsertSqlist(p, 0, 40);	//插入40   表内:40
	InsertSqlist(p, 0, 30);	//插入30   表内:30, 40
	InsertSqlist(p, 0, 10);	//插入10   表内:10, 30, 40
	InsertSqlist(p, 1, 20);	//在第二个位置插入20   表内:10, 20, 30, 40
	print_all(p);		//输出顺序表 10, 20, 30, 40
	DeleteSqlist(p, 1);	//删除第二个位置的数
	print_all(p);		// 表内:10, 30, 40
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值