您的位置:首页 > 理论基础 > 数据结构算法

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

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

希望这些能提供给初学者一些参考。
 
在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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构