题目内容:用程序实现“线性表”数据的初始化、输入、输出、销毁、清空...
个人解法如下:
#define _CRT_SECURE_NO_WARNINGS //防报错
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 100
#define Succeed 1
#define Overflow -1
typedef int Status;
typedef struct
{
int* elem;
int length;
}SqList;
Status InitList_Sq(SqList& L)
{
L.elem = (int*)malloc(sizeof(int) * Maxsize);
if (!L.elem)
return Overflow;
L.length = 0;
return Succeed;
}
void Createlist_Sq(SqList& L)
{
int n, i;
printf("\n请输入数据元素个数:");
scanf("%d", &n);
printf("\n请输入%d个数据元素:\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &L.elem[i]);
L.length++;
}
}
void PrintList_Sq(SqList& L)
{
if (!L.elem)
printf("\n顺序表不存在!");
else if (L.length)
{
printf("\n该顺序表的元素有:\n");
for (int i = 0; i < L.length; i++)
printf("%d\n", L.elem[i]);
}
else
printf("\n顺序表不存在!");
}
void DestroyList_Sq(SqList& L)
{
if (L.elem)
free(L.elem);
L.elem = NULL;
}
void ClearList_Sq(SqList& L)
{
L.length = 0;
}
int main()
{
SqList TargetList;
if (InitList_Sq(TargetList) == Succeed)
{
printf("顺序表初始化成功!\n");
Createlist_Sq(TargetList);
PrintList_Sq(TargetList);
DestroyList_Sq(TargetList);
ClearList_Sq(TargetList);
printf("\n缓存已被清除!");
}
else
printf("\n顺序表初始化失败!");
return 0;
}
运行结果:
本人拙作,请大佬们点评。