问题与代码
/*
*Copyright (c) 2015,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:shun.cpp
*作者:陈梦萍
*完成日期:2015年9月20日
*版本号:v1.0
*
*问题描述: 在原程序的基础上增加:
插入数据元素ListInsert.
删除数据元素ListDelete.
初始化线性表InitList.
销毁线性表DestroyList.
*输入描述:无
*程序输出:若干数据
*/
#include<stdio.h>
#include<malloc.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
} SqList;
void CreateList(SqList *&l, int a[], int n);
void DispList(SqList *l);
bool ListEmpty(SqList *l);
void InitList(SqList *&l);
void DestroyList(SqList *&l);
bool ListInsert(SqList *&l,int i,ElemType e);
bool ListDelete(SqList *&l,int i,ElemType &e);
int main()
{
SqList *sq;
InitList(sq);
ListInsert(sq, 1, 5);
ListInsert(sq, 2, 3);
ListInsert(sq, 1, 4);
DispList(sq);
return 0;
}
void InitList(SqList *&l)
{
l=(SqList *)malloc(sizeof(SqList));
l->length=0;
}
void CreateList(SqList *&l, int a[],int n)
{
int i;
l=(SqList *)malloc(sizeof(SqList));
for(i=0; i<n; i++)
{
l->data[i]=a[i];
}
l->length=n;
}
void DispList(SqList*l)
{
int i=0;
if(ListEmpty(l))
return;
while(i<l->length)
{
printf("%d ",l->data[i]);
i++;
}
printf("\n");
}
bool ListEmpty(SqList *l)
{
if(l->length==0)
{
return 1;
}
else return 0;
}
void DestroyList(SqList *&l)
{
free(l);
}
bool ListInsert(SqList *&l,int i,ElemType e)
{
int j;
if (i<1 || i>l->length+1)
return false;
i--;
for (j=l->length; j>i; j--)
l->data[j]=l->data[j-1];
l->data[i]=e;
l->length++;
return true;
}
bool ListDelete(SqList *&l,int i,ElemType &e)
{
int j;
if (i<1 || i>l->length)
return false;
i--;
e=l->data[i];
for (j=i; j<l->length-1; j++)
l->data[j]=l->data[j+1];
l->length--;
return true;
}
运行结果
知识点总结
在项目一中,我们不断的在原函数的基础之上,添加不同的自定义函数,以实现不同的功能,使函数的功能和作用更加多样化,更加满足我们的需求。