线性表简要提点
- 线性表基于数组创建,利于查找(指定下标即可)。
- 线性表不利于在开头或中间删除或添加元素操作(会移动大量元素)。
C语言实现
#include<>
#include<>
#include<>
#define LIST_INIT_SIZE 100
typedef struct {
int *elemList;
int length;
int listsize;
}Sqlist;
void InitList(Sqlist *Sq)
{
Sq->elemList = (int *)malloc(LIST_INIT_SIZE * sizeof(int));
if (!Sq->elemList)
exit(1);
Sq->length = 0;
Sq->listsize = LIST_INIT_SIZE;
}
void Insert(Sqlist *Sq, int d, int index)
{
int j;
if (index<0 || index>Sq->length)
{
printf("index error\n");
exit(1);
}
if (Sq->length >= LIST_INIT_SIZE)
{
printf("oversize\n");
exit(1);
}
for (j = Sq->length-1;j >= index;j--)
{
Sq->elemList[j + 1] = Sq->elemList[j];
}
Sq->elemList[index] = d;
Sq->length++;
}
int main()
{
Sqlist *L = (Sqlist *)malloc(sizeof(Sqlist *));
InitList(L);
int n, i, v;
printf("Input the size of Sqlist n: \n");
scanf("%d", &n);
printf("Input the %d values: \n", n);
for (i = 0;i < n;i++)
{
scanf("%d", &v);
Insert(L, v, i);
}
printf("The Sqlist contents:\n");
for (i = 0;i < n;i++)
{
printf("%d ", L->elemList[i]);
}
system("pause");
return 0;
}
(附) C++实现
#include<iostream>
using namespace std;
const int LIST_INIT_SIZE = 100;
typedef struct {
int *elemList;
int length;
int listsize;
}Sqlist;
void InitList(Sqlist *Sq)
{
Sq->elemList = new int [LIST_INIT_SIZE];
if (!Sq->elemList)
exit(1);
Sq->length = 0;
Sq->listsize = LIST_INIT_SIZE;
}
void Insert(Sqlist *Sq, int d, int index)
{
int j;
if (index<0 || index>Sq->length)
{
cout<<"index error\n";
exit(1);
}
if (Sq->length >= LIST_INIT_SIZE)
{
cout<<"oversize\n";
exit(1);
}
for (j = Sq->length - 1;j >= index;j--)
{
Sq->elemList[j + 1] = Sq->elemList[j];
}
Sq->elemList[index] = d;
Sq->length++;
}
int main()
{
Sqlist* L = new Sqlist;
InitList(L);
int n, i, v;
cout<<"Input the size of Sqlist n: \n";
cin >> n;
cout << "Input the " << n << " values: \n";
for (i = 0;i < n;i++)
{
cin >> v;
Insert(L, v, i);
}
cout<<"The Sqlist contents:\n";
for (i = 0;i < n;i++)
{
cout<< L->elemList[i]<<' ';
}
cout << endl;
system("pause");
delete L;
return 0;
}