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

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


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

 

在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;
}


你可能感兴趣的:(数据结构)