| 网站首页 | 业界新闻 | 小组 | 交易 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛

```#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100

typedef int Elemtype;
typedef struct SqList
{
Elemtype data[MaxSize];
int length; //顺序表的长度
};
void Init__List(struct SqList *sq);
int Length__List(struct SqList sq);
Elemtype Get__List(struct SqList sq, int index);
int Locate__List(struct SqList sq, int value);
void Insert__List(struct SqList*sq,int index,int value);
void Delete__List(struct SqList *sq, int index);
int main(void)
{

struct SqList sq;
Init__List(&sq);
printf("线性表的长度是%d\n", sq.length);

system("pause");
return 0;
}

void Init__List(struct SqList *sq)
{
//sq = (struct SqList *)malloc(sizeof(struct SqList));  问题:只有把这句注释了,上面的长度是0,否则是垃圾值，是为啥呢
sq->length = 0;
}
/*
typedef struct SqList
{
Elemtype data[MaxSize];
int length; //顺序表的长度
};
*/
//求顺序表的长度
int Length__List(struct SqList sq)
{

return sq.length;
}
/*

*/
Elemtype Get__List(struct SqList sq, int index)
{
if (index <= 0 || index > sq.length)
{
return -1; //-1表示不存在
}

return sq.data[index - 1];
}

int Locate__List(struct SqList sq, int value)
{
for (int i = 1; i <= sq.length; i++)
{
if (sq.data[i - 1] == value)
{
return i - 1;
}
}

return -1;
}
void Insert__List(struct SqList*sq,int index,int value)
{
if (index <= 0 || index > sq->length + 1)
{
printf("插入的位置错误\n");
}

for (int i = sq->length - 1; i >= index - 1; i--)
{
sq->data[i + 1] = sq->data[i];
}
sq->data[index - 1] = value;
sq->length++;
}

void Delete__List(struct SqList *sq, int index)
{
if (index <= 0 || index > sq->length)
{
printf("删除的位置错误\n");
}

for (int i = index - 1; i < sq->length; i++)
{
sq->data[i] = sq->data[i + 1];
}

sq->length--;
}```

struct SqList sq;
struct SqList* p_sq = &sq;
p_sq->length = 0;

struct SqList sq;
struct SqList* p_sq = &sq;
p_sq = malloc(sizeof(struct SqList));
p_sq->length = 0;

```/*
struct SqList* sq;
sq = Init__List();
*/
struct SqList* Init__List()
{
struct SqList* p;
p = (struct SqList *)malloc(sizeof(struct SqList));
if (p!=NULL)
p->length = 0;
return p;
}```
• 4
• 1/1页
• 1