#include <stdio.h>
#include <malloc.h>
#define LIST_MAX_LENGTH 10
typedef struct SequentialList {
int actualLength;
int data[LIST_MAX_LENGTH];
} *SequentialListPtr;
//定义结构体
void outputList(SequentialListPtr paraList) {
for (int i = 0; i < paraList->actualLength; i++) {
printf(“%d “, paraList->data[i]);
}
printf(”\r\n”);
}
//输出数组中各个数据
SequentialListPtr sequentialListInit(int paraData[], int paraLength) {
SequentialListPtr resultPtr = (SequentialList*)malloc(sizeof(SequentialList));
for (int i = 0; i < paraLength; i++)
{
resultPtr->data[i] = paraData[i];
}
resultPtr->actualLength = paraLength;
return resultPtr;
}
//初始化数组
int locateElement(SequentialListPtr paraListPtr, int paraValue)
{
for (int i = 0; i < paraListPtr->actualLength; i++)
{
if (paraListPtr->data[i] == paraValue)
{
return i;
}
}
return -1;
}
//定位给出的数字在数组中的位置
int getElement(SequentialListPtr paraListPtr, int paraPosition) {
if (paraPosition < 0) //检查输入的数字是否小于0
{
printf(“Invalid position: %d.\r\n”, paraPosition);
return -1;
}
if (paraPosition > paraListPtr->actualLength) //检查输入的数字是否超出数组大小
{
printf(“Cannot delete element: the position %d is beyond the list length %d.\r\n”, paraPosition, paraListPtr->actualLength);
return -1;
}
return paraListPtr->data[paraPosition-1];
}
//找出所给顺序表位置上的数字
void clearList(SequentialListPtr paraListPtr)
{
paraListPtr->actualLength = 0;
}
//清空顺序表
void locateElementTest()
{
int tempArray[5] = { 3, 5, 2, 7, 4 };
SequentialListPtr tempList = sequentialListInit(tempArray, sizeof(tempArray)/4);
printf(“---- locateElementTest begins. ----\r\n”);
printf("After initialization, the list is: ");
outputList(tempList);
printf(“now test 3\n”);
int a=locateElement(tempList,3);
if (a != -1)
{
printf(“inuput value rank %d\n”,a+1);
}
else
{
printf(“the value you input dosen’t exit\n”);
}
outputList(tempList);
}
void getElementTest()
{
int tempArray[5] = { 3, 5, 2, 7, 4 };
SequentialListPtr tempList = sequentialListInit(tempArray, sizeof(tempArray)/4);
printf(“---- getElementTest begins. ----\r\n”);
printf("After initialization, the list is: ");
outputList(tempList);
printf(“now test 1\n”);
int b=getElement(tempList, 1);
if (b != -1)
{
printf(“you get %d from that position\n”,b);
}
outputList(tempList);
}
void clearListTest()
{
int tempArray[5] = { 3, 5, 2, 7, 4 };
SequentialListPtr tempList = sequentialListInit(tempArray, sizeof(tempArray)/4);
printf(“---- clearListTest begins. ----\r\n”);
printf("After initialization, the list is: ");
outputList(tempList);
printf(“now clear it”);
clearList(tempList);
outputList(tempList);
printf(“clear sucess”);
}
void main()
{
locateElementTest();
getElementTest();
clearListTest();
}
运行结果: