# 【数据结构复习】线性表

#include <stdio.h>
#include <string.h>
#define  MAXSIZE 10

typedef int ElemType;

typedef struct
{
ElemType data[MAXSIZE];
int length;
}SqList;

// get the element at position
int GetElement(SqList L,  int pos )
{
// check the list and the pos
if (L.length == 0 || pos < 1 || pos > L.length)
{
printf("您的线性表为空或获取位置有误\n");
return false;
}
return  L.data[pos - 1];
}

// insert the element at position
bool InsertElement(SqList L, int pos, ElemType elem)
{
// check the list and the position
if (L.length >= MAXSIZE || pos < 1 || pos > L.length + 1 )
{
printf("您的线性表已满或插入位置有误\n");
return false;
}

if (pos < L.length)
{
for (int index = L.length - 1; index >= pos - 1; index --)
{
L.data[index + 1] = L.data[index];
}
}
L.data[pos - 1] = elem;
L.length++;

return true;
}

// delete the element at position
bool DeleteElement(SqList L, int pos, int elem)
{
// check the list and the position
if (L.length == 0 || pos < 1 || pos > L.length)
{
printf("您的线性表为空或位置有误");
return false;
}
elem = L.data[pos - 1] ;
if (pos < L.length)
{
for (int index = pos; index < L.length ; index++)
{
L.data[index - 1] = L.data[index];
}
}
L.length -- ;
return true;
}

int test()
{
// init the list
SqList list;
for (int index = 0; index < 10; index++)
{
list.data[index] = index;
}
list.length = 10;

int i = GetElement(list, 2);
printf("Get element from the list at position 2 is %d \n", i);
InsertElement(list, 10, 99);
printf("Insert element to the list at position 11 \n");
int elem=0;
DeleteElement(list, 2, elem);
printf("Delete element from the list at position 2 is %d \n", elem);

return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：【数据结构复习】线性表 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)