1.线性表(linear_list):
特点:
在数据元素的非空有限集合中
- 存在惟一的一个被称作“第一个”的数据元素;
- 存在惟一的一个被称作“最后一个”的数据元素;
- 除第一个之外,集合中的每一个数据元素均只有一个前驱
- 除最后一个之外,集合中的每一个数据元素均只有一个后继
2.线性表的顺序表示:用一组地址连续的存储单元依次存储线性表的数据元素
#include <bits/stdc++.h>
using namespace std;
#define LIST_INIT_SIZE 100 /// 线性表存储空间的初始分配量
#define LISTINCREMENT 10 /// 线性表存储空间的分配增量
#define Elemtype int
#define Status int
#define OK 1
#define ERROR -1
#define OVERFLOW -2
typedef struct
{
Elemtype *elem;
int length;
int listsize;
}Sqlist;
Status InitList_Sq(Sqlist &L)
{
L.elem = (Elemtype * )malloc(LIST_INIT_SIZE*sizeof(Elemtype));
if (!L.elem)
{
return OVERFLOW;
}
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
Status DestroyList_Sq(Sqlist &L)
{
if (L.length > 0 )
{
free(L.elem);
free(&L);
}
return OK;
}
Status ClearList_Sq(Sqlist &L)
{
L.length = 0;
return OK;
}
Status IsEmptyList_Sq(Sqlist &L)
{
if (L.length == 0) return OK;
else return ERROR;
}
Status GetLengthList_Sq(Sqlist &L)
{
return L.length;
}
Status GetElem(Sqlist &L,int i,Elemtype &e)
{
if (i < 1 || i > L.length + 1 ) return ERROR;
else
{
e = L.elem[i-1];
return OK;
}
}
Status ListInsert_Sq(Sqlist &L, int i, Elemtype e)
{
if (i < 1 || i > L.length + 1 )return ERROR;
if (L.length >= L.listsize)
{
Elemtype *newbase = (Elemtype *) realloc(L.elem,L.listsize + LISTINCREMENT * sizeof(Elemtype));
if (!newbase)
{
return OVERFLOW;
}
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
int *last = &L.elem[i-1];
for (int *index = &(L.elem[L.length-1]); index >= last; index --)
{
*(index +1) = *index ;
}
*last = e;
++L.length;
return OK;
}
Status ListDeleteByPos_Sq(Sqlist &L,int i,Elemtype &e)
{
if (i < 1 || i > L.length) return ERROR;
int *pos = &L.elem[i-1];
e = *pos;
int *last = L.elem + L.length -1;
for (pos++; pos <= last; pos++)
{
*(pos-1) = *pos;
}
L.length--;
return OK;
}
Status ListDeleteByVal_Sq(Sqlist &L,Elemtype e)
{
int *index = &L.elem[0];
int *last = &L.elem[L.length-1];
for (; index <= last; index++)
{
if (*index == e)
{
for (int *k = index +1; k <= last; k++)
*(k-1) = *k;
L.length--;
index--;///因为p的值已经更新了,需要在判断一次
}
}
return OK;
}
Status ListTraverse_Sq(Sqlist &L)
{
for (int i=0; i<L.length; i++)
{
i<L.length-1 ? printf("%d ",L.elem[i]):printf("%d\n",L.elem[i]);
}
return OK;
}
int main()
{
Sqlist Sq_list;
InitList_Sq(Sq_list);
int n;
scanf("%d",&n);
for (int i=0; i<n; i++)
{
int val;
scanf("%d",&val);
ListInsert_Sq(Sq_list,i+1,val);
}
ListTraverse_Sq(Sq_list);
int dele_val,dele_pos;
scanf("%d",&dele_pos);
ListDeleteByPos_Sq(Sq_list,dele_pos,dele_val);
ListTraverse_Sq(Sq_list);
return 0;
}