顺序表练习

例题:

用顺序表存储一些正整数,输入正整数表示插入数据(例如输入3代表插入3),输入负整数表示删除数据(例如输入-2代表删除2)。输入字符表示退出程序。插入和删除的过程中保持该表递增有序。   

解答;

1.  头文件 seq.h

#ifndef __SEQ_H__ //避免头文件被重复包含
#define __SEQ_H__

#include <stdio.h>
#include <stdlib.h>

#define N 10			 //数组元素的个数

typedef unsigned int datatype;

struct seq{
	datatype arr[N];	 //数组
	int len;			 //实际数据的长度
};


struct seq *seq_init(void);

void seq_insert(struct seq* px,datatype data,int loc);

void display(struct seq* px);

void seq_del(struct seq *px,datatype data);

void seq_replace(struct seq*px,datatype old,datatype new);

void seq_insert_sort(struct seq *px,datatype data);
#endif

2.  函数实现 seq.c

#include "seq.h"

//初始化

struct seq *seq_init(void)
{
	/*在堆中申请空间*/
	struct seq *p = (struct seq *)malloc(sizeof(struct seq));
	if(p == NULL)
	{
		perror("malloc error");
		return NULL;
	}

	/*设置当前实际数据的长度为0*/
	p->len = 0;

	return p;
}

//插入功能函数

void seq_insert(struct seq* px,datatype data,int loc)
{
	/*判断位置是否合法*/	
	if(loc < 0 || loc >px->len)
	{
		printf("传入的位置不合法...\n");
		return;
	}

	/*判断是否存满*/
	if(px->len == N)
	{
		printf("抱歉,已存满...\n");
		return;
	}

	/*移动数据,腾出空位*/
	int i;
	//因为数组下标是从0开始的,所以最后一个有效元素的下标len - 1
	for(i =	px->len - 1;i >= loc;i--)
	{
		px->arr[i+1] = px->arr[i];
	}

	/*存入数据*/
	px->arr[loc] = data;

	/*有效数据个数+1*/
	px->len++;
}

//插入并排序函数

void seq_insert_sort(struct seq *px,datatype data)
{
	int i;
	/*遍历顺序表*/
	for(i = 0;i < px->len;i++)
	{
		/*比对数据,确定位置*/
		if(data < px->arr[i])
		  break;
	}
	/*调用上述的插入函数*/
	seq_insert(px,data,i);	
}

//遍历展示

void display(struct seq* px)
{
	printf("遍历结果:\n");
	int i;
	for(i = 0 ;i < px->len;i++)
	  printf("%d ",px->arr[i]);

	printf("\n");
}

//删除函数

void seq_del(struct seq *px,datatype data)
{
	int i = 0,j = 0;//i用来遍历,j用来移动
	/*遍历整个顺序表*/
	while(i < px->len)
	{
		/*找到要删除的数据的位置*/
		if(px->arr[i] == data)
		{
			for(j = i + 1;j <= px->len - 1;j++)
			  px->arr[j-1] = px->arr[j];

			/*实际数据长度-1*/
			px->len--;
			continue;//为了删除后续可能还存在的相同数据
		}
		i++;	//往后继续遍历去找符合该数值的数据
	}
}

3.  main函数实现 test.c

#include "seq.h"

int main(void)
{
	/*初始化*/
	struct seq *px = seq_init();
	if(px == NULL)
	{
		return -1;
	}

	int d;
	int ret;

	while(1)
	{
		ret = scanf("%d",&d);
		if(ret == 0)
		  break;

		if(d > 0)
		{
			/*插入数据并排序*/
			seq_insert_sort(px,d);
		}
		else if(d < 0)
		{
			/*删除数据*/
			seq_del(px,-d);//将负整数转换为正整数传入到顺序表中
		}
		display(px);
	}

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值