(编程训练)再回首,数据结构——顺序表上的编程训练

最近在复习数据结构,顺便看看大一的时候写的代码,看完之后比当初有了更加深刻的体会。


希望这些能提供给初学者一些参考。

 

在VC++6.0下可运行,当初还写了不少注释。


/*C语言描述
建立一有序的顺序表,并实现下列操作:
1.把元素x插入表中并保持有序;
2.查找值为x的元素,若找到将其删除;
3.输出表中各元素的值。
*/


#include <stdio.h>
#define MAXSIZE 20

//建立顺序表结构体
typedef struct seqlist
{
	int elem[MAXSIZE];
	int length;
}SeqList;

//初始化顺序表
void IniList(SeqList *l)
{
	l->length = 0;
}

//将元素插入表中并保持有序
void InsList(SeqList *l, int n)
{
	int i = 0, j;
	
	while (n > l->elem[i] && i < l->length)
		i++;
	
	for (j = l->length - 1; j >= i; j--)
		l->elem[j+1] = l->elem[j];
	
	l->elem[i] = n;
	
	(l->length)++;
}

//查找某元素是否在表中
int CheckList (SeqList l, int n)
{
	int i = 0;
	
	while (i < l.length && n != l.elem[i])
		i++;
	
	if (i < l.length)
		return i;
	
	return -1;
}

//查找并删除某个元素
void DelList (SeqList *l, int n)
{
	int  j;
	if (n < 0 || n > l->length - 1)
	{
		printf ("ERROR!!!Can't check this elem\n");
		return ;
	}
	
	for (j = n + 1; j < l->length; j++)
		l->elem[j-1] = l->elem[j];
	
	(l->length)--;
}

//输出表中各元素
void PrintList(SeqList l)
{
	int i;
	for (i = 0; i < l.length; i++)
	{
		printf ("%d  ", l.elem[i]);
	}
	printf ("\n");
}

int main ()
{
	SeqList list;
	int index, element;
	
	IniList(&list);		//初始化
	
	printf ("Enter the first value in the list: ");		//输入元素
	scanf ("%d", &element);
	
	printf ("Enter the others in the list(end with 0): ");
	while (0 != element)
	{
		InsList(&list, element);		//插入元素
		scanf ("%d", &element);
	}
	
	PrintList(list);	//列表输出元素
	
	printf ("Enter the value to deleted: ");
	scanf ("%d", &element);
	
	index = CheckList(list, element);	//查找元素
	if (-1 == index)
	{
		printf ("%d is not in the list \n", element);
	}
	else
		DelList(&list, index);		//若找到,则删除元素
	
	PrintList(list);	//再次列表输出各个元素
	
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值